simone
simone

Reputation: 119

How to update in Laravel

I'm having some problem to implement the update in my Laravel app. In my blade file I have a modal where I show the fields in a . Every row as a button that opens another modal where every fields should be updated. So this is the blade file:

<form action="{{ action('AnamController@update', $par->id_par) }}" method="put" class="form-horizontal">
    {{csrf_field()}}
    <input name="input_name" value="Par" hidden />

    <div class="col-lg-12">
        <div class="form-group">
            <label class="control-label col-lg-4">Name:</label>
            <div class="col-lg-6">
                <input id="name" name="name" type="text" class="form-control" value="{{$par->name}}"/>
            </div>
        </div>
    </div>
    <!--other things-->
</form>

But this return to me an error. "Property [id_par] does not exist on this collection instance" and if I insert a foreach statement when I press the button edit to open the modal I always see the first field present in the db. So what I have to do?

Thanks

EDIT This is the route:

Route::post('/anam/{id}, AnamController@update')->name('anam');

EDIT 2 I try to implement the update function to see if the update works. But I have error MethodNotAllowedHttpException

This is what I wrote:

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

    $par = Par::find($id);
    $par->name = $request->input('name');
    $par->save();

    return redirect('/anam');
}

Upvotes: 0

Views: 258

Answers (2)

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

Your route has to be this :

Route::put('/anam/{id}, AnamController@update')->name('anam');

not

Route::post('/anam/{id}, AnamController@update')->name('anam');

AND in your form use this

<form action="{{ action('AnamController@update', $par->id_par) }}" method="POST" class="form-horizontal">
{{csrf_field()}}
{{ method_field('PUT') }}

EDIT :

You might have an issue with the name of your primary key :

is your primary key of the Par Model is id_par ?

check in your console that the request is on the right id (ex : /aname/10)

then try to add a dd($id); in your controller to see if the id you have is the right one.

PS: You should try a ressource controller with automatic Model Binding

https://laravel.com/docs/5.7/routing#implicit-binding

Upvotes: 0

nakov
nakov

Reputation: 14248

First of for an update you need to change the form element method should be post and then add a blade directive @method('put') for newer laravel versions or {{ method_field('PUT') }} for older within the form.

Please share some more code not only the view so we can see what causes the error that you get.

Upvotes: 1

Related Questions