Laravel 9 Middleware Example Tutorial

Laravel 9 middleware example; Through this tutorial, i am going to show you how to create and how to use middleware in laravel 9 apps.

Laravel 9 Create and Use Middleware Example Tutorial

Use the below given steps to create and use middleware in laravel 9 apps:

  • 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

Run the following command on command prompt to create middleware in laravel apps:

php artisan make:middleware CheckStatus

Step 2 – Register Middleware

Then visit to app/http/directory and open kernel.php. And register middleware in this file:

<?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 – Build Logic Into Your Middleware File

Visit app/http/middleware and open checkStatus.php middleware file. And build logic into your middleware file:

<?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

Makea route and use custom middleware with routes for filter every http request:

 
 //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

Make one method name home and add this method on HomeController.php file, which is placed on app/Http/Controllers/ directory:

<?php
 
 namespace App\Http\Controllers;
 
 use Illuminate\Http\Request;
 class HomeController extends Controller
 {
     public function home()
     {
         dd('You are active');
     }
 }
?>

Conclusion

Laravel 9 middleware tutorial, you have learned how to create and use custom middleware in laravel 9 apps.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *