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.
- Laravel Breeze – Simple authentication starter kit
- Laravel Jetstream – Scaffolding for Laravel apps
- Laravel Passport – API authentication via OAuth2
- Laravel Sanctum – Simple API authentication
- Spatie Laravel Permission – Role and permission management
- Laravel Cashier – Subscription billing with Stripe
- Laravel Scout – Full-text search using Algolia
- Laravel Socialite – OAuth authentication (Google, Facebook, etc.)
- Laravel Excel – Excel import and export for Laravel
- Laravel Horizon – Redis queues monitoring
- Laravel Nova – Admin panel for Laravel
- Laravel Fortify – Backend authentication for Laravel
- Laravel Vapor – Serverless deployment on AWS
- Laravel Telescope – Debugging assistant for Laravel
- Laravel Dusk – Browser testing
- Laravel Mix – API for compiling assets
- Spatie Laravel Backup – Backup management
- Laravel Livewire – Building dynamic UIs
- Spatie Laravel Media Library – Manage media uploads
- Laravel Excel – Excel spreadsheet handling
- Laravel Debugbar – Debug tool for Laravel
- Laravel WebSockets – Real-time communication
- Spatie Laravel Sitemap – Generate sitemaps
- Laravel Spark – SaaS scaffolding
- Laravel Envoy – Task runner for deployment
- Spatie Laravel Translatable – Multilingual model support
- Laravel Backpack – Admin panel
- Laravel AdminLTE – Admin interface template
- Laravel Collective Forms & HTML – Simplified form and HTML generation
- Spatie Laravel Analytics – Google Analytics integration
- Laravel Eloquent Sluggable – Automatically create slugs
- Laravel Charts – Chart integration
- Laravel Auditing – Track changes in models
- Laravel JWT Auth – JSON Web Token authentication
- Laravel Queue Monitor – Monitor job queues
- Spatie Laravel Query Builder – Filter, sort, and include relationships in Eloquent queries
- Laravel Datatables – jQuery Datatables API
- Laravel Localization – Multilingual support for views and routes
- Laravel Acl Manager – Access control list manager
- Laravel Activity Log – Record activity in your app
- Laravel Roles – Role-based access control
- Spatie Laravel Tags – Tagging models
- Laravel Installer – CLI installer for Laravel
- Laravel Breadcrumbs – Generate breadcrumbs in Laravel
- Laravel Mailgun – Mailgun integration for Laravel
- Laravel Trustup Model History – Store model change history
- Laravel Deployer – Deployment automation tool
- Laravel Auth – Custom authentication guards
- Laravel CORS – Cross-Origin Resource Sharing (CORS) support
- Laravel Notifications – Send notifications through multiple channels
- Spatie Laravel Http Logger – Log HTTP requests
- Laravel Permission Manager – Manage permissions easily
- Laravel Stubs – Customize default stubs in Laravel
- Laravel Fast Excel – Speed up Excel exports
- Laravel Image – Image processing
- Spatie Laravel Backup Server – Centralize backups for Laravel apps
- Laravel Forge API – Manage servers through the Forge API
- Laravel Blade SVG – Use SVGs in Blade templates
- Laravel Ban – Ban/unban users from your application
- Laravel API Response – Standardize API responses
- Laravel SEO – Manage SEO meta tags
- Laravel Settings – Store and retrieve settings
- Laravel DOMPDF – Generate PDFs
- Laravel Turbo – Full-stack framework for building modern web apps
- Spatie Laravel Event Sourcing – Event sourcing implementation
- Laravel Jetstream Inertia – Jetstream’s Inertia.js integration
- Laravel Envoy Tasks – Task automation
- Laravel Likeable – Like/dislike functionality
- Laravel GeoIP – Determine visitor’s geographic location
- Laravel Country State City – Dropdowns for country, state, and city
- Laravel Hashids – Generate short unique hashes
- Laravel Repository – Repository pattern for Laravel
- Laravel UUID – UUID generation for models
- Spatie Laravel Medialibrary Pro – Enhanced media management
- Laravel Queue Monitor – Monitor Laravel job queues
- Laravel User Activity – Monitor user activity
- Laravel DB Snapshots – Create database snapshots
- Laravel Twilio – Twilio integration
- Laravel Roles – Role-based permission handling
- Laravel Translatable – Add translations to Eloquent models
- Laravel Teamwork – Manage teams in multi-tenant apps
- Laravel Full Text Search – Add full-text search to Laravel models
- Laravel File Manager – File and media management
- Laravel User Timezones – Automatically detect user time zones
- Laravel ChartsJS – Render charts with ChartsJS
- Laravel Stripe – Stripe API integration
- Laravel PDF Generator – PDF generation
- Laravel Elasticsearch – Elasticsearch integration
- Laravel Simple Qrcode – Generate QR codes
- Laravel Timezone – Manage timezones and conversions
- Laravel Collective API – API management for Laravel
- Laravel Rest API Boilerplate – REST API starter kit
- Laravel Multi Auth – Multi-authentication functionality
- Laravel Voyager – Admin panel for Laravel
- Laravel Voyager Database – Database manager for Voyager
- Laravel Categories – Handle categories for models
- Laravel Multitenancy – Multi-tenancy implementation
- Laravel Access Control – Advanced access control for users
- Laravel Menus – Menu management
- Laravel Translatable Routes – Multilingual route handling