Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel form won't PATCH, only POST - nested RESTfull Controllers, MethodNotAllowedHttpException

I am trying to allow users to edit their playlist. However, whenever I try to execute the PATCH request, I get the MethodNotAllowedHttpException error. (it is expecting a POST)

I have set up RESTful Resource Controllers:

Routes.php:

Route::resource('users', 'UsersController');
Route::resource('users.playlists', 'PlaylistsController');

This should give me access to: (as displayed through php artisan routes)

URI                                        | Name                   | Action
PATCH users/{users}/playlists/{playlists}  | users.playlists.update | PlaylistsController@update

However, when I try to execute the following form, I get the MethodNotAllowedHttpException error:

/users/testuser/playlists/1/edit

{{ Form::open(['route' => ['users.playlists.update', $playlist->id], 'method' => 'PATCH' ]) }}
{{ Form::text('title', $playlist->title) }}
{{ Form::close() }}

If I remove 'method'=> 'PATCH' I don't get an error, but it executes my public function store() and not my public function update()

like image 940
maarten Avatar asked Sep 15 '14 22:09

maarten


4 Answers

In Laravel 5 and up:

<form method="POST" action="patchlink">
    @method('patch')
    . . .
</form>
like image 106
Sean Avatar answered Nov 12 '22 19:11

Sean


Write {!! method_field('patch') !!} after form:

<form method="POST" action="patchlink">
     {!! method_field('patch') !!}
     . . .
</form>

Official documentation for helper function method_field()

like image 20
Alex Lomia Avatar answered Nov 12 '22 21:11

Alex Lomia


Since html forms support only GET and POST you need to add an extra hidden field to the form called _method in order to simulate a PATCH request

<input type="hidden" name="_method" value="PATCH">
like image 8
Nenad Avatar answered Nov 12 '22 19:11

Nenad


As suggested by @Michael A in the comment above, send it as a POST

<form method="POST" action="patchlink">
     <input type="hidden" name="_method" value="PATCH">

Worked for me.

like image 5
MCH Avatar answered Nov 12 '22 19:11

MCH