Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel define a put/patch route as the same route name

In Laravel it's quite handy to quickly generate a load of routes by using a route resource:

Route::resource('things'ThingsController');

This will produce all the necessary RESTful routes for CRUD operations. One of these is the PUT/PATCH route which might be defined as follows:

PUT/PATCH things/{id} ThingsController@update things.update

I've read around that it's better to explicitly define each of your routes rather than use a route resource but how would I define the PUT/PATCH route above. I understand that I can do

Route::put('thing/{id}', ['as' => 'things.update']);

or

Route::patch('thing/{id}', ['as' => 'things.update']);

But the second would overwrite or conflict with the first allowing the things.update route name to only refer to either a PUT or PATCH request. How can I explicitly create the combined PUT/PATCH route as created by the resource route?

like image 682
harryg Avatar asked Dec 05 '14 13:12

harryg


People also ask

What is the difference between put and patch in Laravel?

PUT is a method of modifying resource where the client sends data that updates the entire resource . PATCH is a method of modifying resources where the client sends partial data that is to be updated without modifying the entire data.

How can I get route name in Laravel?

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request: $route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();

Why do we use name in route in Laravel?

Named routes is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.


2 Answers

After tedious searching, try the following;

Route::match(array('PUT', 'PATCH'), "/things/{id}", array(
      'uses' => 'ThingsController@update',
      'as' => 'things.update'
));

This allows you to restrict request via an array of Verbs.

Or you can limit the resource as so;

Route::resource('things', 'ThingsController',
        array(
           'only' => array('update'), 
           'names' => array('update' => 'things.update')
        ));

Both should provide the same result, but please note they are not tested.

like image 151
Matt Burrow Avatar answered Nov 15 '22 19:11

Matt Burrow


This work for me

Route::match(['put', 'patch'],'thing/{id}', 'ThingsController@update');
like image 20
Rojith Randula Peiris Avatar answered Nov 15 '22 19:11

Rojith Randula Peiris