Laravel Middleware

Marickian
By -
0
Laravel Middleware Guide for Laravel 11

Laravel Middleware Guide

Middleware in Laravel is used to filter HTTP requests before they reach the application logic. They can handle authentication, logging, CORS, and other request modifications.

1. Creating Middleware

You can create middleware using Artisan:

php artisan make:middleware CheckUserRole

2. Registering Middleware

In Laravel 11, middleware is registered in the bootstrap/app.php file. Example:

use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
  ->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
      'auth.custom' => \App\Http\Middleware\CustomAuthMiddleware::class
    ]);
  })
  ->create();

3. Applying Middleware to Routes

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', function () {
        return 'Dashboard';
    });
});

4. Global, Route, and Group Middleware

Middleware can be applied globally, to specific routes, or to route groups.

5. Middleware Parameters

You can pass parameters to middleware:

public function handle($request, Closure $next, $role)
{
    if (!Auth::user() || Auth::user()->role !== $role) {
        abort(403);
    }
    return $next($request);
}

6. Auth Guards in Middleware

Laravel allows multiple authentication guards using Auth::guard(). Example usage:

public function handle($request, Closure $next)
{
    if (!Auth::guard('admin')->check()) {
        return redirect('/login');
    }
    return $next($request);
}

The Auth::guard() method lets you define different authentication guards for users, admins, or other roles.

7. Using Middleware in API Routes

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

8. Middleware Priority

Middleware can have different priorities, and you can control the order in which they are executed. This is important when you have multiple middleware that need to run in a specific order. In Laravel 11, you set middleware priority in the bootstrap/app.php file:

use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
  ->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
      'auth.custom' => \App\Http\Middleware\CustomAuthMiddleware::class
    ]);

    $middleware->priority([
      \App\Http\Middleware\CustomAuthMiddleware::class,
      \App\Http\Middleware\AnotherMiddleware::class,
    ]);
  })
  ->create();

9. Middleware Groups

Middleware groups allow you to apply a set of middleware to your routes with a single key. This is useful for organizing middleware that should always run together.

use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
  ->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
      'auth.custom' => \App\Http\Middleware\CustomAuthMiddleware::class,
    ]);

    $middleware->group([
      'web' => [
          \App\Http\Middleware\EncryptCookies::class,
          \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
          \Illuminate\Session\Middleware\StartSession::class,
          // more middleware
      ],
      'api' => [
          'throttle:api',
          \Illuminate\Routing\Middleware\SubstituteBindings::class,
          // more middleware
      ],
    ]);
  })
  ->create();

10. Excluding Middleware

If there are certain routes where you don't want to apply middleware, you can exclude those routes by listing them in the middleware's constructor:

public function __construct()
{
    $this->middleware('auth')->except('login', 'register');
}

11. Conclusion

Middleware is a powerful feature in Laravel that helps control the flow of HTTP requests and responses. It enhances security, authentication, and data processing before reaching controllers.

Post a Comment

0Comments

Post a Comment (0)