Fernando
Fernando

Reputation: 7

How to create another update function with PUT and PATCH request in one route?

I am currently developing a project using laravel 5.0. Lets say i have a route like this in my route.php:

Route::resource('user', 'UserController', ['except' => ['index', 'create', 'store', 'destroy']]);
Route::get('user/{user}/posts', 'UserController@indexUserPosts');
Route::get('user/{user}/changepassword', 'UserController@changePassword');
Route::put('user/{user}/changepassword', 'UserController@updatePassword');
Route::patch('user/{user}/changepassword', 'UserController@updatePassword');

Where if i access http:// localhost:8000/user/{username} it will trigger the show method, and if i access http://localhost:8000/user/{username}/edit it will trigger the edit method which will give a PUT & PATCH request to http:// localhost:8000/user/{user}. But in this phase, the user can only edit their personal informations, for the password i want to create a new editPassword which gives also PUT & PATCH request. And im not sure if i write the route correctly above.

So, the question is how do i manually write the route in the route.php file according to laravel's convention?

And should i send the PUT & PATCH request to http: //localhost:8000/user/{user} again (which i think will crash with the PUT & PATCH request from the edit function) or should i send the PUT & PATCH request to http: //localhost:8000/user/{user}/changepassword ?

Thanks in advance. :)

Upvotes: 0

Views: 678

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

First you don't need to repeat patch function. It's enough to use put. The second thing is, whenever you create any extra urls and user resource, you need to put them before resource route, so your routes file should look like this:

Route::get('user/{user}/posts', 'UserController@indexUserPosts');
Route::get('user/{user}/changepassword', 'UserController@changePassword');
Route::put('user/{user}/changepassword', 'UserController@update');
Route::resource('user', 'UserController', ['except' => ['index', 'create', 'store', 'destroy']]);

So now, when user go to edit page, they will have link to edit password page, when they click on it they will go to GET user/{user}/changepassword and when they fill form and click update they will go to PUT user/{user}/changepassword'

Upvotes: 1

Related Questions