skip to Main Content

So when I try to access the update function inside a resource controller, when I hit submit to go there (posts/{id}) I go to the show function of the controller (witch has the same path (posts/{id}).
How can I go the the update path, and access the update function?

So here is the view with its from of the edit function, that will "update" the title:

@extends('layouts.app')

@section('content')

    <h1>Edit Post</h1>

    <form method="get" action="/posts/{{$post->id}}">
        @csrf
        <input type="hidden" name="_method" value="PUT">
        <input type="text" name="title" placeholder="Enter title" value="{{$post->title}}">
        <input type="submit" name="submit">
    </form>

@endsection

And here is the update function of the controller, that will get the values from the upper view and update the post with that id:

public function update(Request $request, $id)
{
    //
    $post = Post::findOrFail($id);
    $post->update($request->all());
    return redirect('/posts');
}

And this is the show function that is going to run after I hit submit, instead of the update:

public function show($id)
{
    //
    $post = Post::findOrFail($id);
    return view('posts.show', compact('post'));
}

The view of show function, in case you need it:

@extends('layouts.app')

@section('content')

    <h1>{{$post->title}}</h1>

@endsection

When I hit submit it should check first the update function of controller, and render its code, because both update function and show function have the same path posts/{id}.
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    So instead of method="get", use method="post" if u already used get for show function, because both show and update have the same path: posts/{$id}.


  2. First of all you have in the web.php file the POST path so you should change the method tag of your form in this way:

    <form method="POST">
    

    Remove the invisible field where you specify a method, that’s not how it’s done.

    <input type="hidden" name="_method" value="PUT">
    

    Next I recommend that you use the route() function to specify which route you want to make the request to. This way you can use the names of your routes.

    <form method="POST" action="{{ route('posts.update', ['id' => $post->id]) }}">
    

    In your web.php file you must specify your update path as follows:

    Route::post('update/{id}', [PostsController::class, 'update'])->name('posts.update');
    

    I hope it has helped you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search