Middleware groups in Laravel 5.2
This is a series of posts that showcase new features and aha moments in Laravel 5.2
1. Implicit Route Model Binding
2. Simplified Eloquent Global Scopes
3. Append Scheduled Tasks Output
5. Middleware Groups
Laravel 5.2 has a new feature that allows you group several route middleware under a single name/key thus helping you assign several middleware to a route/group of routes at once.
Laravel 5.2 comes shipped with two major middleware groups named web
and api
.
Let’s take a look.
1. Open AppHttpKernel.php
. You will see something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], 'api' => [ 'throttle:60,1', ], ]; |
2. Open routes.php
, you will see something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | This route group applies the "web" middleware group to every route | it contains. The "web" middleware group is defined in your HTTP | kernel and includes session state, CSRF protection, and more. | */ Route::group(['middleware' => ['web']], function () { // }); Route::group(['middleware' => 'web'], function () { Route::auth(); Route::get('/home', 'HomeController@index'); }); |
Every route you stuff inside this Route group will have all the middleware grouped under web
have effect on it.
Also, for your API routes, you can also just apply the api
middleware group like so:
1 2 3 4 5 6 |
Route::group(['middleware' => ['api']], function() { Route::get('/api/vi/songs', 'SongController@index'); Route::get('/api/vi/song/{id}', 'SongController@fetchData'); }); |
By default, it applies a rate limit of 60 requests per minute to all the routes above.
You can apply other middleware to the api
group by just adding it in the api
array in Kernel.php
.
It’s that simple.
Please, let me know if you have any questions or observations in the comments section below.
- How to build your own Youtube – Part 10 - August 1, 2016
- How to build your own Youtube – Part 9 - July 25, 2016
- How to build your own Youtube – Part 8 - July 23, 2016
- How to build your own Youtube – Part 6 - July 6, 2016
- Introducing Laravel Password v1.0 - July 3, 2016
- How to build your own Youtube – Part 5 - June 28, 2016
- How to build your own Youtube – Part 4 - June 23, 2016
- How to build your own Youtube – Part 3 - June 15, 2016
- How to build your own Youtube – Part 2 - June 8, 2016
- How to build your own Youtube – Part 1 - June 1, 2016