Laravel Custom middleware


Creating custom middleware in Laravel involves a few straightforward steps. Middleware in Laravel acts as a filter for HTTP requests entering your application. You can use it to perform various tasks like authentication, logging, and modifying request or response objects.

Here’s a step-by-step guide to creating custom middleware:

  1. Generate Middleware: Use the Artisan command to generate a new middleware class. For example, to create middleware that checks if a user is an admin, you can use:

    php artisan make:middleware CheckAdmin

    This will create a new file in the app/Http/Middleware directory.

  2. Define Middleware Logic: Open the newly created middleware file (app/Http/Middleware/CheckAdmin.php) and implement the logic you want. The handle method is where you define what the middleware should do:

    namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class CheckAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { if (!auth()->user() || !auth()->user()->isAdmin()) { return redirect('home'); } return $next($request); } }

    In this example, if the user is not an admin, they are redirected to the 'home' route.

  3. Register Middleware: After creating the middleware, you need to register it. You can do this in the app/Http/Kernel.php file.

    Add the middleware to the $routeMiddleware array if you want to use it for specific routes:

    protected $routeMiddleware = [ // Other middleware 'admin' => \App\Http\Middleware\CheckAdmin::class, ];

    Alternatively, you can add it to the $middleware array if you want it to apply globally:

    protected $middleware = [ // Other global middleware \App\Http\Middleware\CheckAdmin::class, ];
  4. Use Middleware in Routes: You can apply your middleware to routes or route groups. Here’s how you use it in your routes file (routes/web.php):

    Route::get('/admin', function () { // Only accessible to admins })->middleware('admin');

    Or in route groups:

    Route::middleware(['admin'])->group(function () { Route::get('/admin/dashboard', function () { // Admin dashboard }); });

And that’s it! Your custom middleware is now set up and ready to use in your Laravel application.