简体   繁体   中英

Laravel: Form model binding and resource controller error

I'm building a really simple CRUD in laravel just to learn something about this framework. It works all like a charm but I can't make the update function of a controller work properly.

Here my situation:

1) I build a resource controller using artisan command.

2) I build a form view using blade and I Open the form with this code:

<!-- Form -->
@if($mode=="edit")
    {{ Form::model($task, array('route'=>array('task.update',$task->id),'files'=>true)) }}
@else
    {{ Form::open(array('route'=>'task.store','files'=>true)) }}
@endif

It works great and every field are filled with the right data. The generate url of the form's action is:

http://localhost/mysite/task/2

The problem is that when I submit this form I get this error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException

Someone can understand why? Can I help you with more information?

You need 'method' => 'put'.

{{ Form::model($task, array('route' => array('task.update', $task->id), 'files' => true, 'method' => 'PUT')) }}

As you can see here.

http://laravel.com/docs/controllers#resource-controllers

Verb:     PUT/PATCH
Path:     /resource/{id}
action:   update
route:    resource.update

EDIT: To trigger the update()-action you must send a PUT or PATCH-request to the route resource.update , in your case task.update .

You have a problem with the form action. Assuming you have a route like this:

Route::post('task/update/{id}, function()
{

});

Then, your model-bound form should be:

{{ Form::model($task, array('url'=>array('task/update',$task->id),'files'=>true)) }}

The only error in your code is that you did not passed PUTor PATCH as HTTP method for your form submission to server.

Symfony \\ Component \\ HttpKernel \\ Exception \\ MethodNotAllowedHttpException is triggered on such states.

a demo model form will be as

 Form::model($name_model, array('action' => array('Controller_name@method', $argument), 'files' => true, 'method' => 'PUT'))

or with route name as

Form::model($name_model, array('route' => array('route.name', $argument), 'files' => true, 'method' => 'PUT'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM