In this tutorial you will learn about the Laravel 8 Middleware Example Tutorial and its application with practical example.
In this Laravel 8 Middleware Example Tutorial, I will show you how to create custom middleware and to use in laravel application. In this tutorial you will learn to create and use custom middlewalre in laravel. In this article I will share example to create simple custom middleware to check user status.
Laravel 8 Middleware Example Tutorial
In this step by step laravel middleware tutorial I will demonstrate you with example of active or inactive users. Now we will call middleware in routes to restrict logged user to access that routes.
- Step 1: Create Middleware
- Step 2 – Register Middleware
- Step 3 – Implement Logic Into Your Middleware File
- Step 4 – Add Route
- Step 5 – Add Method in Controller
Step 1: Create Middleware
In this step we will first create a custom middleware in laravel based project. So let’s open your command prompt and run following command :
1 |
php artisan make:middleware CheckStatus |
Step 2 – Register Middleware
Now, go to app/http/kernel.php and register your custom middleware here :
app/Http/Kernel.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { .... /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ .... 'checkStatus' => \App\Http\Middleware\CheckStatus::class, ]; } |
Step 3 – Implement Logic Into Your Middleware File
After successfully register your middleware in laravel project, go to app/http/middleware and implement your logic here :
app/Http/Middleware/CheckStatus.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http\Middleware; use Closure; class CheckStatus { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (auth()->user()->status == 'active') { return $next($request); } return response()->json('Your account is inactive'); } } |
Step 4 – Add Route
Now, we will add some route with middleware as following
1 2 3 4 5 6 7 8 9 10 |
//routes/web.php use App\Http\Controllers\HomeController; use App\Http\Middleware\CheckStatus; Route::middleware([CheckStatus::class])->group(function(){ Route::get('home', [HomeController::class,'home']); }); |
Step 5 – Add Method in Controller
Now we will create a method to check active or inactive users.
app/Http/Controllers/HomeController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function home() { dd('You are active'); } } ?> |