Laravel define a put/patch route as the same route

2019-06-18 08:17发布

问题:

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?

回答1:

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.



回答2:

This work for me

Route::match(['put', 'patch'],'thing/{id}', 'ThingsController@update');