Guards in Laravel

What are Guards in Laravel?

Guards in Laravel control how users are authenticated for each request. They define the authentication technique, like session-based or token-based. They also collaborate with authentication drivers, such as web, API, or custom ones, to protect your application.


Origin

Guards are an essential component of Laravel's authentication system, designed to handle a broad variety of authentication use cases and scenarios.


Why are Guards Used?

  1. Supports Multiple Authentication Methods: Apps can use various ways to authenticate users, including sessions and API tokens.
  2. Improves Security: Ensures that suitable authentication procedures are used for certain routes or application areas.
  3. Enables Role Management: Custom guards allow you to manage numerous user roles using tailored authentication techniques.

Best Practices.

  1. Configure Guards: Properly define and manage guards in the config/auth.php file for a clear and maintainable configuration.
  2. Combine with Middleware: Guards can be used in conjunction with route middleware to implement granular access control across your application.
  3. Test Custom Guards: Thoroughly test any custom guards to verify smooth integration and good functionality in your application.

Example in Action

Define guards in config/auth.php:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
],

Use a guard for authentication:

if (Auth::guard('api')->check()) {
    return response('Authenticated', 200);
}

Read more