Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding multiple middleware to Laravel route

Tags:

php

laravel

Per laravel doc, I can add the auth middleware as follows:

Route::group(['middleware' => 'auth'], function () {     Route::get('/', function ()    {         // Uses Auth Middleware     });      Route::get('user/profile', function () {         // Uses Auth Middleware     }); }); 

I've also seen middleware added as follows:

Route::group(['middleware' => ['web']], function() {   // Uses all Middleware $middlewareGroups['web'] located in /app/Http/kernel.php?   Route::resource('blog','BlogController'); //Make a CRUD controller }); 

How can I do both?

PS. Any comments providing insight on what the bottom four lines of code are doing would be appreciated

like image 725
user1032531 Avatar asked Nov 26 '16 20:11

user1032531


People also ask

Can we apply two middleware on a single route?

To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once.

Can we use multiple middleware?

Middlewares can be chained. We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app.

How many types of middleware are there in Laravel?

There are two types of Middleware in Laravel. The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.


1 Answers

To assign middleware to a route you can use either single middleware (first code snippet) or middleware groups (second code snippet). With middleware groups you are assigning multiple middleware to a route at once. You can find more details about middleware groups in the docs.

To use both (single middleware & middleware group) you can try this:

Route::group(['middleware' => ['auth', 'web']], function() {   // uses 'auth' middleware plus all middleware from $middlewareGroups['web']   Route::resource('blog','BlogController'); //Make a CRUD controller }); 
like image 98
krlv Avatar answered Sep 20 '22 02:09

krlv