How to create Middleware in Laravel
This tutorial is for How to create Middleware in Laravel. Laravel provides two types of Middlewares. We will create Middleware in Laravel with step by step example to understand easily.
Command prompt open and your project directory inside run this command:
step 1 : Create Middleware
php artisan make:middleware Admin
Navigate to the following directory. app/Http/Middleware/Admin.php
#app/Http/Middleware/Admin.php
public function handle($request, Closure $next)
{
if(auth()->user()->isAdmin == 1) {
return $next($request);
}
return redirect('home')->with('error','You have not admin access');
}
step 2 : Now, open this file app/Http/Kernel.php
<?php
#app\Http\Kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'admin' => \App\Http\Middleware\Admin::class,
];
?>
step 3 : Add Route
<?php
#routes/web.php
Route::get('admin/routes', 'HomeController@admin')->middleware('admin');
?>
You Multiple middleware use. so you can route group create:
<?php
#routes/web.php
Route::group(['middleware' => ['admin','auth']], function () {
Route::get('admin/routes', 'HomeController@admin');
});
====== OR ======
/* Multiple Middlewares in Single line */
Route::get('admin/routes', 'HomeController@admin')->middleware(['admin','auth']);
?>