Laravel 8: InvalidArgumentException: Auth guard [admin] is not defined

  jetstream, laravel, mysql, php

I’m trying to build a multiple authentication system with Laravel Jetstream (Users & Admins). Normal user login is working as it should, however the admin login is showing me this error.

InvalidArguementException (Screenshot)

I did some research and tried clearing cache by running couple of commands,

php artisan config:cache
php artisan config:clear

But it didn’t solved the problem.

Here’s my config/auth.php

<?php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

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

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

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

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => AppModelsUser::class,
        ],
        
        'admins' => [
            'driver' => 'eloquent',
            'model' => AppModelsAdmin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
        'admins' => [
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    'password_timeout' => 10800,

];

AdminStatefulGuard.php

<?php

namespace AppGuards;

interface AdminStatefulGuard extends Guard
{
    /**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param  array  $credentials
     * @param  bool  $remember
     * @return bool
     */
    public function attempt(array $credentials = [], $remember = false);

    /**
     * Log a user into the application without sessions or cookies.
     *
     * @param  array  $credentials
     * @return bool
     */
    public function once(array $credentials = []);

    /**
     * Log a user into the application.
     *
     * @param  IlluminateContractsAuthAuthenticatable  $user
     * @param  bool  $remember
     * @return void
     */
    public function login(Authenticatable $user, $remember = false);

    /**
     * Log the given user ID into the application.
     *
     * @param  mixed  $id
     * @param  bool  $remember
     * @return IlluminateContractsAuthAuthenticatable|bool
     */
    public function loginUsingId($id, $remember = false);

    /**
     * Log the given user ID into the application without sessions or cookies.
     *
     * @param  mixed  $id
     * @return IlluminateContractsAuthAuthenticatable|bool
     */
    public function onceUsingId($id);

    /**
     * Determine if the user was authenticated via "remember me" cookie.
     *
     * @return bool
     */
    public function viaRemember();

    /**
     * Log the user out of the application.
     *
     * @return void
     */
    public function logout();
}

AdminController.php

<?php

namespace AppHttpControllers;

use IlluminateContractsAuthStatefulGuard;
use IlluminateHttpRequest;
use IlluminateRoutingController;
use IlluminateRoutingPipeline;
use AppActionsFortifyAttemptToAuthenticate;
use LaravelFortifyActionsEnsureLoginIsNotThrottled;
use LaravelFortifyActionsPrepareAuthenticatedSession;
use AppActionsFortifyRedirectIfTwoFactorAuthenticatable;
use AppHttpResponsesLoginResponse;
use LaravelFortifyContractsLoginViewResponse;
use LaravelFortifyContractsLogoutResponse;
use LaravelFortifyFeatures;
use LaravelFortifyFortify;
use LaravelFortifyHttpRequestsLoginRequest;

class AdminController extends Controller
{
    /**
     * The guard implementation.
     *
     * @var IlluminateContractsAuthStatefulGuard
     */
    protected $guard;

    /**
     * Create a new controller instance.
     *
     * @param  IlluminateContractsAuthStatefulGuard  $guard
     * @return void
     */
    public function __construct(StatefulGuard $guard)
    {
        $this->guard = $guard;
    }

    public function loginForm(){

        return view('auth.login', ['guard' => 'admin']);
    }

    /**
     * Show the login view.
     *
     * @param  IlluminateHttpRequest  $request
     * @return LaravelFortifyContractsLoginViewResponse
     */
    public function create(Request $request): LoginViewResponse
    {
        return app(LoginViewResponse::class);
    }

    /**
     * Attempt to authenticate a new session.
     *
     * @param  LaravelFortifyHttpRequestsLoginRequest  $request
     * @return mixed
     */
    public function store(LoginRequest $request)
    {
        return $this->loginPipeline($request)->then(function ($request) {
            return app(LoginResponse::class);
        });
    }

    /**
     * Get the authentication pipeline instance.
     *
     * @param  LaravelFortifyHttpRequestsLoginRequest  $request
     * @return IlluminatePipelinePipeline
     */
    protected function loginPipeline(LoginRequest $request)
    {
        if (Fortify::$authenticateThroughCallback) {
            return (new Pipeline(app()))->send($request)->through(array_filter(
                call_user_func(Fortify::$authenticateThroughCallback, $request)
            ));
        }

        if (is_array(config('fortify.pipelines.login'))) {
            return (new Pipeline(app()))->send($request)->through(array_filter(
                config('fortify.pipelines.login')
            ));
        }

        return (new Pipeline(app()))->send($request)->through(array_filter([
            config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
            Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
            AttemptToAuthenticate::class,
            PrepareAuthenticatedSession::class,
        ]));
    }

    /**
     * Destroy an authenticated session.
     *
     * @param  IlluminateHttpRequest  $request
     * @return LaravelFortifyContractsLogoutResponse
     */
    public function destroy(Request $request): LogoutResponse
    {
        $this->guard->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return app(LogoutResponse::class);
    }
}

FortifyServiceProvider.php

<?php

namespace AppProviders;

use IlluminateContractsAuthStatefulGuard;
use AppActionsFortifyAttemptToAuthenticate;
use AppActionsFortifyRedirectIfTwoFactorAuthenticatable;
use AppHttpControllersAdminController;
use Auth;

use AppActionsFortifyCreateNewUser;
use AppActionsFortifyResetUserPassword;
use AppActionsFortifyUpdateUserPassword;
use AppActionsFortifyUpdateUserProfileInformation;
use IlluminateCacheRateLimitingLimit;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRateLimiter;
use IlluminateSupportServiceProvider;
use LaravelFortifyFortify;

class FortifyServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->when([AdminController::class, AttemptToAuthenticate::class, RedirectIfTwoFactorAuthenticatable::class])
            ->needs(StatefulGuard::class)
            ->give(function(){
                return Auth::guard('admin');
            });
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Fortify::createUsersUsing(CreateNewUser::class);
        Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
        Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
        Fortify::resetUserPasswordsUsing(ResetUserPassword::class);

        RateLimiter::for('login', function (Request $request) {
            return Limit::perMinute(5)->by($request->email.$request->ip());
        });

        RateLimiter::for('two-factor', function (Request $request) {
            return Limit::perMinute(5)->by($request->session()->get('login.id'));
        });
    }
}

Source: Laravel

Leave a Reply