Understanding Guards in Laravel: A Comprehensive Guide to Managing Multiple User Roles

Yash Kumar Prasad
4 min readOct 18, 2024

--

Introduction:

In any modern web application, user authentication plays a crucial role. Laravel, being a powerful and flexible PHP framework, offers a robust way to handle authentication using guards. Guards in Laravel help developers manage multiple authentication drivers for different types of users within the same application. Whether you’re dealing with administrators, vendors, or customers, guards make it easy to manage these various user roles. In this article, we’ll dive deep into what guards are, how they work, and how you can use them to streamline your authentication system.

What Are Guards in Laravel?

In Laravel, guards are a mechanism to define how users are authenticated for each request. Essentially, they specify how authentication should be handled in terms of drivers (e.g., session-based, token-based) and user providers (e.g., Eloquent models, database queries).

Each guard manages its own state and user, allowing you to implement different authentication methods and restrictions for different user types in the same application. This is especially useful in situations where you have multiple roles that need their own unique access and functionality, such as:

  • Admins: Can manage the entire application.
  • Vendors: Have limited access to manage products or services.
  • Customers: Can browse and purchase items.

Key Concepts of Guards in Laravel

Before diving into the implementation of guards, it’s essential to understand the two key elements that work closely with guards:

  1. Driver: This determines how the authentication will be handled. Laravel comes with a few built-in drivers like session and token. Custom drivers can also be implemented based on specific requirements.
  2. Provider: This defines how the user is retrieved from the database. Typically, the Eloquent user provider is used, but Laravel also supports database queries and custom user providers.

Setting Up Guards in Laravel

Step 1: Configure Guards in auth.php

Guards are defined in the config/auth.php file. By default, Laravel includes a web guard (session-based authentication) and an api guard (token-based authentication). You can define custom guards based on your application’s needs.

Here’s an example of how to configure guards for different roles, like admins and vendors:

// config/auth.php

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

'admin' => [
'driver' => 'session',
'provider' => 'admins',
],

'vendor' => [
'driver' => 'session',
'provider' => 'vendors',
],

'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],

'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],

'vendors' => [
'driver' => 'eloquent',
'model' => App\Models\Vendor::class,
],
],

In the configuration above:

  • We’ve created separate guards for admin and vendor, both using the session driver.
  • Each guard references a specific user provider (admins, vendors), allowing us to authenticate against different models.

Step 2: Create Models for Different User Roles

After configuring guards, you’ll need to define models for the different user roles. For example, if you have an Admin and a Vendor, you can create models using Artisan:

php artisan make:model Admin
php artisan make:model Vendor

Each model will represent the corresponding database table where user data is stored. You can now define authentication logic for each user role.

Step 3: Set Middleware for Each Guard

To ensure that each user type is routed to the appropriate areas of your application, you can assign middleware to routes. Middleware checks which guard should be used for a particular request.

Here’s how to define middleware in your web.php or api.php routes:

// web.php

Route::group(['middleware' => 'auth:admin'], function () {
// Admin routes
Route::get('/admin/dashboard', [AdminController::class, 'dashboard']);
});

Route::group(['middleware' => 'auth:vendor'], function () {
// Vendor routes
Route::get('/vendor/dashboard', [VendorController::class, 'dashboard']);
});

The auth:admin and auth:vendor middleware ensure that only authenticated users under the respective guards can access the routes.

Using Guards in Controllers

In your controllers, you can check the authentication status for specific guards by using the auth() helper. Here’s an example of how you can authenticate and access data for different user roles:

// In AdminController

public function dashboard()
{
$admin = auth('admin')->user(); // Access the authenticated admin
return view('admin.dashboard', compact('admin'));
}

// In VendorController

public function dashboard()
{
$vendor = auth('vendor')->user(); // Access the authenticated vendor
return view('vendor.dashboard', compact('vendor'));
}

This ensures that only users authenticated through the admin or vendor guard can access their respective data.

Testing and Debugging Guards

When working with multiple guards, debugging becomes crucial to ensure that the correct guard is being used for each request. You can test guards by using the built-in artisan commands:

php artisan tinker

// Log in as an admin
auth('admin')->attempt(['email' => 'admin@example.com', 'password' => 'password']);
auth('admin')->user(); // Get the currently authenticated admin

Make sure to thoroughly test each guard’s functionality in your application to avoid authentication issues.

Conclusion

Guards in Laravel provide a flexible and powerful way to manage multiple user roles within your application. Whether you’re building a multi-role system for admins, vendors, or customers, guards help streamline your authentication processes while ensuring security and scalability. With the steps outlined in this guide, you should be well-equipped to implement guards in your next Laravel project.

If you found this guide helpful, feel free to share it with others, and leave a comment if you have any questions or need further assistance!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response