Laravel is a powerful PHP framework that simplifies web application development. One of its key features is a robust authentication system. At the core of this system lies the concept of guards. Understanding guards is crucial for building applications with multiple user roles or authentication mechanisms.
What are Laravel Guards?
In Laravel, a guard defines how users are authenticated for each request. It acts as a layer that determines how to check if a user is logged in and which user provider to use to retrieve user information.
Think of a guard as the authentication driver that manages user sessions or tokens.
Laravel comes with two main authentication drivers:
- Session Guard – Used for typical web applications where login status is maintained using sessions and cookies.
- Token Guard – Used for APIs where authentication is done using tokens, typically
API TokensorJWT.
How Guards Work in Laravel
Guards rely on user providers. The user provider defines how users are retrieved from storage, typically a database.
- Guard → Handles authentication mechanism.
- User Provider → Handles retrieving user data from the storage.
For example, in config/auth.php:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
webguard uses thesessiondriver and retrieves users from theusersprovider.apiguard uses thetokendriver with the same user provider.
Default Guard
The default guard is defined in config/auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
Laravel uses the web guard for web requests unless specified otherwise.
Why Guards Are Useful
- Multiple Authentication Systems: You can have different guards for users, admins, and API clients.
- Flexible Authentication: Choose between session-based, token-based, or custom authentication.
- Role-Based Access Control: Guards make it easier to restrict certain areas of your application to specific users.
Creating Custom Guards
Sometimes, the default guards are not enough. You can create custom guards.
Example: A custom guard for admin users:
- Define a new guard in
config/auth.php:
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
- Create Admin model:
php artisan make:model Admin -m
- Protect routes using middleware:
Route::middleware('auth:admin')->group(function () {
Route::get('/admin/dashboard', [AdminController::class, 'index']);
});
Now only authenticated admins can access the /admin/dashboard route.
Using Guards in Code
You can explicitly use a guard in your controllers or middleware:
// Check if a user is logged in using the 'web' guard
if (Auth::guard('web')->check()) {
$user = Auth::guard('web')->user();
}
// Authenticate using the 'admin' guard
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
Common Use Cases of Guards
- Multiple User Roles
- Users, Admins, Managers, etc. Each with separate authentication.
- API Authentication
- API tokens or JWT for stateless authentication.
- Third-Party Authentication
- Social login or external authentication systems.
Tips for Working with Guards
- Always specify the guard in routes if you have multiple guards.
- Don’t mix session guards and token guards unless necessary.
- Use middleware
auth:guard_nameto protect routes. - Test each guard independently to ensure correct authentication behavior.
Conclusion
Laravel guards are a powerful tool for managing authentication in complex applications. They allow you to:
- Define multiple ways to authenticate users.
- Protect different types of users and routes.
- Easily extend authentication with custom guards.
By understanding guards and providers, you can implement secure, flexible, and maintainable authentication systems in your Laravel applications.
What is a Guard in Laravel?
It specifies the logic of authentication (e.g., using sessions, tokens, etc.).
Difference between Guards and Providers in Laravel?
Providers → Define how users are retrieved from the database.
‘guards’ => [
‘web’ => [
‘driver’ => ‘session’,
‘provider’ => ‘users’,
],
‘admin’ => [
‘driver’ => ‘session’,
‘provider’ => ‘admins’,
],
],
Where are Guards defined in Laravel?
config/auth.php file under the guards array.What are the default Guards in Laravel?
web → Uses sessions and cookies (for browser authentication).api → Uses tokens (like Passport, Sanctum, JWT).Can you create a custom Guard in Laravel?
Steps:
Define guard in
config/auth.php.Create custom authentication logic (via provider or custom class).
Register the guard in
AuthServiceProvider.How do you switch between multiple Guards?
Auth::guard('guard_name') method.Example:
Auth::guard('admin')->attempt($credentials);How to get currently logged-in user from a specific guard?
Difference between Auth::check() and Auth::guard()->check()?
Auth::check() → Uses default guard (web).Auth::guard('api')->check() → Uses the specified guard.How to protect routes with different Guards?
routes/web.php or routes/api.php:Route::middleware('auth:admin')->group(function () { // Only admin users can access });When should you use multiple Guards?
Example:
admin, customer, vendor.How is Laravel Guard related to Middleware?
Example:
auth:admin middleware checks login with admin guard.What is the default Guard in Laravel and how to change it?
web.To change: update
defaults.guard in config/auth.php.How to log out a user from a specific Guard?
How to authenticate users without using Guard directly?
attempt(), login(), or once() methods:Auth::attempt(['email' => $email, 'password' => $password]);Example use case: Guards with Admin and User logins
Web guard → Handles normal user login.
This prevents conflicts when both roles exist in the system.
