A Guard in Laravel is an authentication mechanism that determines how users are authenticated for each request.
Guard = Authentication Method
Why do we use Guards?
Guards are used when your application has different types of users, for example:
- Customers
- Admins
- Employees
Default Guard:
config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],The default guard is web.
Types of Guards
1. Web Guard
Used for normal website login (session-based authentication).
Auth::guard('web')->attempt([
'email' => $email,
'password' => $password
]);Check if logged in:
if (Auth::guard('web')->check()) {
echo "Logged In";
}Get logged-in user:
$user = Auth::guard('web')->user();2. API Guard:
Used for API authentication.
Route::middleware('auth:api')->get('/profile', function () {
return Auth::user();
});If using Sanctum:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});How to Create Multiple Guards
Suppose you have two tables:
usersadmins
Step 1: Create Admin Model
php artisan make:model AdminStep 2: Add Guard in config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],Step 3: Add Provider:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],Step 4: Login with Admin Guard
if (Auth::guard('admin')->attempt([
'email' => $email,
'password' => $password
])) {
return redirect('/admin/dashboard');
}Step 5: Protect Admin Routes
Route::middleware('auth:admin')->group(function () {
Route::get('/admin/dashboard', function () {
return "Welcome Admin";
});
});| Method | Description |
|---|---|
Auth::guard('web')->attempt() | Login user |
Auth::guard('web')->check() | Check if user is logged in |
Auth::guard('web')->user() | Get authenticated user |
Auth::guard('web')->id() | Get user ID |
Auth::guard('web')->logout() | Logout user |