6

I want to use more than one method in a single route using laravel. I'm try this way but when i dd() it's show the plan string.

Route::get('/user',[
'uses' => 'AppController@user',
'as'   => 'useraccess',
'roles'=> 'HomeController@useroles', 
]);

When i dd() 'roles' option it's show the plan string like this.

"roles" => "HomeController@useroles"

my middleware check the role this way.

 $actions=$request->route()->getAction();
 $roles=isset($actions['roles'])? $actions['roles'] : null;
Gabrielle-M
  • 1,037
  • 4
  • 17
  • 39

2 Answers2

22

The simplest way to accept multiple HTTP methods in a single route is to use the match method, like so:

Route::match(['get', 'post'], '/user', [
    'uses' => 'AppController@user',
    'as'   => 'useraccess',
    'roles'=> 'HomeController@useroles', 
]);

As for your middleware, to check the HTTP request type, a tidier way would be:

$method = request()->method();

And if you need to check for a specific method:

if (request()->isMethod('post')) {
    // do stuff for post methods
}
Mark
  • 1,255
  • 1
  • 13
  • 25
1

Here's how you can do multiple methods on a single route:

Route::get('/route', 'RouteController@index');
Route::post('/route', 'RouteController@create');
Route::put('/route', 'RouteController@update');
/* Would be easier to use
* Route::put('/route/{route}', 'RouteController@update');
* Since Laravel gives you the Model of the primary key you've passed
* in to the route.
*/
Route::delete('/route', 'RouteController@destroy');

If you've written your own middleware, you can wrap the routes in a Route::group and apply your middleware to those routes, or individual routes respectively.

Route::middleware(['myMiddleware'])->group(function () {
    Route::get('/route', 'RouteController@index');
    Route::post('/route', 'RouteController@create');
    Route::put('/route', 'RouteController@update');
});

Or

Route::group(['middleware' => 'myMiddleware'], function() {
    Route::get('/route', 'RouteController@index');
    Route::post('/route', 'RouteController@create');
    Route::put('/route', 'RouteController@update');
});

Whichever is easier for you to read.

https://laravel.com/docs/5.6/routing#route-groups