In Laravel, authentication guards define how users are authenticated for each request. By default, Laravel ships with a web
guard (for sessions and cookies) and an api
guard (for token-based authentication). However, you can create custom authentication guards for specific authentication needs, such as using different user types (e.g., admins and regular users) or custom authentication logic.
Steps to Create a Custom Authentication Guard
1. Modify auth.php
Configuration
The config/auth.php
file contains the authentication guards and providers configuration. You’ll need to define a custom guard here.
Example: Create a custom admin
guard for admin users.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ], // Custom admin guard 'admin' => [ 'driver' => 'session', 'provider' => 'admins', // Use a custom provider ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], // Custom provider for admin 'admins' => [ 'driver' => 'eloquent', 'model' => App\Models\Admin::class, ], ], |
In this configuration:
- A new
admin
guard is defined with asession
driver (same asweb
). - A new
admins
provider is defined, using theAdmin
model for authentication.
2. Create the Admin Model
You’ll need a model to represent the admins
table. Create a model for Admin
using Laravel’s Artisan command:
1 |
php artisan make:model Admin |
Then, define the Admin
model (e.g., app/Models/Admin.php
):
1 2 3 4 5 6 7 8 9 10 |
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { protected $guard = 'admin'; // Add any specific admin properties here } |
3. Create an Admin Login Controller
Next, create a controller for handling admin authentication. You can extend Laravel’s Auth
functionality:
1 |
php artisan make:controller AdminAuthController |
In AdminAuthController.php
, add methods to handle login, logout, and authentication:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AdminAuthController extends Controller { public function showLoginForm() { return view('auth.admin-login'); } public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::guard('admin')->attempt($credentials)) { return redirect()->intended('/admin/dashboard'); } return back()->withErrors(['email' => 'Login failed, please try again.']); } public function logout() { Auth::guard('admin')->logout(); return redirect('/admin/login'); } } |
4. Routes for Admin Authentication
In your routes/web.php
file, add routes to handle the admin login and logout:
1 2 3 4 5 |
use App\Http\Controllers\AdminAuthController; Route::get('admin/login', [AdminAuthController::class, 'showLoginForm'])->name('admin.login'); Route::post('admin/login', [AdminAuthController::class, 'login']); Route::post('admin/logout', [AdminAuthController::class, 'logout'])->name('admin.logout'); |
5. Admin Dashboard Route (Middleware Protection)
Ensure that the admin dashboard is protected by the admin
guard. You can do this by adding middleware to routes for admin areas:
1 2 3 4 5 |
Route::middleware('auth:admin')->group(function () { Route::get('admin/dashboard', function () { return view('admin.dashboard'); })->name('admin.dashboard'); }); |
6. Admin Login View
Create the resources/views/auth/admin-login.blade.php
view for the admin login page:
1 2 3 4 5 6 7 8 9 10 11 12 |
<form method="POST" action="{{ route('admin.login') }}"> @csrf <div> <label for="email">Email:</label> <input type="email" name="email" id="email" required autofocus> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password" required> </div> <button type="submit">Login</button> </form> |
7. Custom Guard Usage
Now, whenever you need to authenticate admin users, use the admin
guard:
1 2 3 4 5 6 7 |
// Check if an admin is authenticated if (Auth::guard('admin')->check()) { // The admin is logged in } // Get the authenticated admin user $admin = Auth::guard('admin')->user(); |
Summary of Steps:
- Define a Custom Guard: Modify
config/auth.php
to add a custom guard and provider. - Create a Model: Set up a model like
Admin
to represent the users for that guard. - Create a Controller: Handle login, logout, and authentication logic.
- Set Up Routes: Define routes for the login, logout, and admin dashboard.
- Create Login View: Build a form for admin login.
- Protect Admin Routes: Use middleware to protect routes.
Output:
The output of setting up custom authentication guards in Laravel involves a series of results visible at different stages of the process, such as when users attempt to authenticate, access protected routes, or perform certain actions.
1. Login Page (Admin Login Form)
When you navigate to the custom admin login route (e.g., /admin/login
), you will see a login form that allows the admin to enter their email and password:
1 2 3 4 5 6 7 8 9 10 11 12 |
<form method="POST" action="{{ route('admin.login') }}"> @csrf <div> <label for="email">Email:</label> <input type="email" name="email" id="email" required autofocus> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password" required> </div> <button type="submit">Login</button> </form> |
2. Successful Admin Login
When the admin successfully logs in by entering the correct email and password, they will be redirected to the admin dashboard (/admin/dashboard
). The dashboard page could look like this:
1 2 |
<h1>Welcome to the Admin Dashboard</h1> <p>You are successfully logged in as an admin.</p> |
3. Failed Admin Login
If the admin enters invalid credentials (wrong email or password), the system will display an error message and reload the login page:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<form method="POST" action="{{ route('admin.login') }}"> @csrf <div> <label for="email">Email:</label> <input type="email" name="email" id="email" required autofocus> <span class="error">Login failed, please try again.</span> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password" required> </div> <button type="submit">Login</button> </form> |
4. Accessing Protected Routes (Dashboard) Without Authentication
If an admin tries to access the dashboard (/admin/dashboard
) without being logged in, they will be redirected to the login page with an error message or redirection logic:
1 |
<p>Please log in to access the admin dashboard.</p> |
This happens because the dashboard route is protected by the auth:admin
middleware, which requires authentication through the admin
guard.
5. Successful Logout
After logging in as an admin, when the admin logs out (via /admin/logout
), they will be logged out successfully and redirected to the login page or a designated logout page:
1 |
<p>You have been successfully logged out. Please log in again if needed.</p> |
6. Checking Authentication in Code
In your code, when you check if the admin is authenticated using the custom admin
guard:
1 2 3 4 5 6 7 |
if (Auth::guard('admin')->check()) { // The admin is logged in return "Admin is logged in!"; } else { // The admin is not logged in return "No admin is logged in!"; } |
The output will reflect whether an admin is logged in or not based on the session:
- If logged in:
"Admin is logged in!"
- If not logged in:
"No admin is logged in!"
7. Redirects and Middleware Output
When the auth:admin
middleware is applied to the dashboard route, and an unauthenticated admin tries to access it, they will be redirected back to the login page (/admin/login
) with appropriate redirection messages.
Summary of Outputs:
- Admin Login Page: Displays the custom login form.
- Successful Login: Redirects to the admin dashboard with a success message.
- Failed Login: Shows an error message on the login form.
- Accessing Protected Route Without Login: Redirects to the login page.
- Successful Logout: Logs out the admin and redirects to the login page.
- Code Checks: Outputs whether the admin is logged in or not.