Hi guys, this tutorial will cover on how to create middleware in laravel.
If you guys forget the syntax on how to create a project using laravel, you guys can go to this link.
Create project using Laravel
Alright so let start.
The syntax for creating middleware is
php artisan make:middleware Middlewarename
You should see the middleware at App/Http/Controllers/Middleware
Let said that we want to create a route that only accessible to admin.
1) Create a middleware (php artisan make:middleware Middlewarename)
2) Go to web.php and register a new route.
Route::get('admin', function(){
echo "You have access";
});
3) Go to middleware that just being created and put session inside
4) Register your middleware in kernel.php
'admin' => \App\Http\Middleware\MiddlewareClassName::class
Note that the namespace path is depends where you store your middleware. Change it according to where you save your middleware
5) Edit web.php to use the middleware that we just created.
Route::get('admin', function(){
echo "You have access";
})->middleware('admin');
6) You should be good to go
By the way, you can also group your route using one middlware.
Route::group (['middleware' => ['admin']], function() {
Route::get('admin', function(){
echo "You have access";
});
});
Thanks for watching my blog. Do follow me on google+ or like my facebook page for more! :)
Obstrum Facebook Page
EmoticonEmoticon