<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Precious Ibeagi</title>
    <description>The latest articles on DEV Community by Precious Ibeagi (@preciousaang).</description>
    <link>https://dev.to/preciousaang</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F305878%2F45428eb4-8e84-4422-b7b3-f0c51ba4063d.jpeg</url>
      <title>DEV Community: Precious Ibeagi</title>
      <link>https://dev.to/preciousaang</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/preciousaang"/>
    <language>en</language>
    <item>
      <title>Multi-guard authentication with Laravel 12</title>
      <dc:creator>Precious Ibeagi</dc:creator>
      <pubDate>Sun, 11 May 2025 00:04:11 +0000</pubDate>
      <link>https://dev.to/preciousaang/multi-guard-authentication-with-laravel-12-1jg3</link>
      <guid>https://dev.to/preciousaang/multi-guard-authentication-with-laravel-12-1jg3</guid>
      <description>&lt;p&gt;In this tutorial i will walk you through implementing multiguard authentication using laravel 12+. &lt;/p&gt;

&lt;p&gt;Below are the steps we will have to follow. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create the model and migration for both admin and users.&lt;/li&gt;
&lt;li&gt;Create the required guards.&lt;/li&gt;
&lt;li&gt;Define the routes and controllers.&lt;/li&gt;
&lt;li&gt;
Configure the redirects for the guards. &lt;/li&gt;
&lt;li&gt;Logout&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Creating the model
&lt;/h2&gt;

&lt;p&gt;We need to have the models we want to create. Make sure that the models extend from the &lt;code&gt;Illuminate\Foundation\Auth\User&lt;/code&gt; class&lt;/p&gt;

&lt;h3&gt;
  
  
  User model
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{

    use HasFactory, Notifiable;


    protected $fillable = [
        'name',
        'email',
        'password',
    ];


    protected $hidden = [
        'password',
        'remember_token',
    ];


    protected function casts(): array
    {
        return [
            'email_verified_at' =&amp;gt; 'datetime',
            'password' =&amp;gt; 'hashed',
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Admin model
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{

    use HasFactory, Notifiable;


    protected $fillable = [
        'name',
        'email',
        'password',
    ];


    protected $hidden = [
        'password',
        'remember_token',
    ];


    protected function casts(): array
    {
        return [
            'email_verified_at' =&amp;gt; 'datetime',
            'password' =&amp;gt; 'hashed',
        ];
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Create the required guards
&lt;/h2&gt;

&lt;p&gt;In config/auth.php, define the required guards. The default guard is &lt;strong&gt;web&lt;/strong&gt; while we will define and extra one as &lt;strong&gt;admin&lt;/strong&gt;. Also here we are adding a new admins provider pointing to the &lt;code&gt;App\Models\Admin&lt;/code&gt; class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; 'guards' =&amp;gt; [
        'web' =&amp;gt; [
            'driver' =&amp;gt; 'session',
            'provider' =&amp;gt; 'users',
        ],
        'admin' =&amp;gt; [
            'driver' =&amp;gt; 'session',
            'provider' =&amp;gt; 'admins',
        ],
    ],

'providers' =&amp;gt; [
        'users' =&amp;gt; [
            'driver' =&amp;gt; 'eloquent',
            'model' =&amp;gt; env('AUTH_MODEL', App\Models\User::class),
        ],

        'admins' =&amp;gt; [
            'driver' =&amp;gt; 'eloquent',
            'model' =&amp;gt; App\Models\Admin::class,
        ],
    ],

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Define the routes and controllers.
&lt;/h2&gt;

&lt;p&gt;Next we define our routes. So here we have the the basic routes. You'll notice that we have the custom guard that we defined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

use App\Http\Controllers\AdminDashboardController;
use App\Http\Controllers\AdminLoginController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LoginController;
use Illuminate\Support\Facades\Route;

Route::middleware('guest')-&amp;gt;group(function () {
    Route::get('login', [LoginController::class, 'loginForm'])-&amp;gt;name('login');
    Route::post('login', [LoginController::class, 'login'])-&amp;gt;name('login-user');
});

Route::middleware('guest:admin')-&amp;gt;group(function () {
    Route::get('/admin/login', [AdminLoginController::class, 'loginForm'])-&amp;gt;name('admin.login');
    Route::post('/admin/login', [AdminLoginController::class, 'login'])-&amp;gt;name('admin.login-admin');
});


Route::middleware('auth')-&amp;gt;get('dashboard', DashboardController::class)-&amp;gt;name('dashboard');
Route::middleware('auth:admin')-&amp;gt;get('/admin/dashboard', AdminDashboardController::class)-&amp;gt;name('admin.dashboard');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;LoginController&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public function loginForm()
    {
        return view('login');
    }

    public function login()
    {
        $user = User::first();
        Auth::login($user);

        return redirect()-&amp;gt;route('dashboard');
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;AdminLoginController&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Controllers;

use App\Models\Admin;
use Illuminate\Support\Facades\Auth;

class AdminLoginController extends Controller
{
    public function loginForm()
    {
        return view('admin.login');
    }

    public function login()
    {
        $admin = Admin::first();
        Auth::guard('admin')-&amp;gt;login($admin);
        return redirect()-&amp;gt;route('admin.dashboard');
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configure the redirects for the guards
&lt;/h2&gt;

&lt;p&gt;You'll notice that when you are not logged in and you try to access the /admin/dashboard as a guest you get redirected to /login instead of /admin/login. So how do we get redirected to the desired urls?&lt;/p&gt;

&lt;p&gt;So for that we have to replace the auth and guest aliases in bootstrap/app.php.&lt;br&gt;
So auth aliases the &lt;code&gt;\Illuminate\Auth\Middleware\Authenticate' middleware while the guest aliases the&lt;/code&gt;\Illuminate\Auth\Middleware\RedirectIfAuthenticated' middleware. &lt;br&gt;
To configure the redirects, we are going to create our own Authenticate and RedirectIfAuthenticated middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:middleware Authenticate
php artisan make:middleware RedirectIfAuthenticated

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now replace the aliases with these new middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

use App\Http\Middleware\Authenticate;
use App\Http\Middleware\RedirectIfAuthenticated;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    -&amp;gt;withRouting(
        web: __DIR__ . '/../routes/web.php',
        commands: __DIR__ . '/../routes/console.php',
        health: '/up',
    )
    -&amp;gt;withMiddleware(function (Middleware $middleware) {
        $middleware-&amp;gt;alias([
            'guest' =&amp;gt; RedirectIfAuthenticated::class,
            'auth' =&amp;gt; Authenticate::class,
        ]);
    })
    -&amp;gt;withExceptions(function (Exceptions $exceptions) {
        //
    })-&amp;gt;create();


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now for the RedirectIfAuthenticated middleware, in the handle method we just have to set the required destination route if the requesting guard is admin or web.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\RedirectIfAuthenticated as MiddlewareRedirectIfAuthenticated;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfAuthenticated extends MiddlewareRedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)-&amp;gt;check()) {
                switch ($guard) {
                    case 'admin':
                        return redirect()-&amp;gt;route('admin.dashboard');
                        break;
                    default:
                        return redirect()-&amp;gt;route('dashboard');
                }
            }
        }

        return $next($request);
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now for the for the Authenticate middleware it's a bit different. We have to modify the &lt;code&gt;$redirectTo&lt;/code&gt; parameter of the &lt;code&gt;AuthenticationException&lt;/code&gt; that is thrown when the &lt;code&gt;unauthenticated&lt;/code&gt; method is called&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Middleware;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as MiddlewareAuthenticate;

class Authenticate extends MiddlewareAuthenticate
{
    protected function unauthenticated($request, array $guards)
    {

        foreach ($guards as $guard) {
            switch ($guard) {
                case 'admin':
                    throw new AuthenticationException(redirectTo: route('admin.login'));
                    break;
                default:
                    throw new AuthenticationException(redirectTo: route('login'));
            }
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Logout
&lt;/h3&gt;

&lt;p&gt;To logout you just call the guards.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Auth::guard('admin')-&amp;gt;logout();
Auth::guard('web')-&amp;gt;logout();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;And voilà. We now have redirects working as they should. You now have a working multi-guard authentication system. You can add as many models as you choose. You can access the code &lt;a href="https://github.com/preciousaang/multiguard-auth" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>authentication</category>
      <category>laravel</category>
      <category>php</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
