Search code examples
phpsymfonylaravel-5.7

Laravel 5.7 : Update method return "No message"


I have tried everything and I can't figure out where comes my mistake.

the update() method doesn't update anaything, i only get back "No message" error...

Here's Routes in web.php:

Route::get('/user/edit/{id}', ['as' => 'users.edit', 'uses' => 'UserAdController@edit']); Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController@update']);

the view users/edit.blade.php :

<div class="container">
        <br>
        <h3>Edit your ad</h3>
        <br>

        <form method="post" action="{{route('users.update', $ad->id)}}">
            <input name="_method" type="hidden" value="PATCH">
            {{ method_field('post') }}
            <div class="form-group">
                <label for="title">Title</label>
                <input type="text" name="title" class="form-control" id="title" value="{{$ad->title}}">
            </div>
            <div class="form-group">
                <label for="title">Price</label>
                <input type="text" name="price" class="form-control" id="title" value="{{$ad->price}}">
            </div>
            <div class="form-group">
                <label for="content">Your content</label>
                <textarea name="content" class="form-control" id="content" rows="3">{{$ad->content}}</textarea>
            </div>
            <div class="form-group">
                <input type="submit" value="Update" class="btn btn-info">
            </div>
        </form>
</div>
@endsection

Update method from UserAdController:

public function update($id, Request $request){

    $request->validate([
        'title'=>'required',
        'price'=> 'required|integer',
        'content' => 'required'
    ]);

    $data = \App\Ad::find($id);
    $data->title = $request->get('title');
    $data->price = $request->get('price');
    $data->content = $request->get('content');
    $data->save();

    return redirect()->back()->with('success', 'Data updated');

}

Solution

  • I'm not a laravel dev. I just stumbled on the documentation. You should also add the csrf field to your blade

    In edit.blade.php, add this after the opening <form> tag

    {{csrf_field()}}
    

    Also the parameters in your update method aren't well arranged

    It should be

    public function update(Request $request, $id) { 
    
    
    }
    

    The second parameter($id), comes from what you've defined as your routes in web.php file

    Route::post('/user/update/{id}', ['as' => 'users.update', 'uses' =>'UserAdController@update']);
    

    Where {id} would be replaced by the original id