Why do two guards in laravel affect each other?

Viewed 390

For my e-commerce app I use the default guard for user and made another one for the control panel admin but logging in or logging out a user affects the status in admin control panel as well and the opposite is true. Why is this?

Here is my auth file:

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

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


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

Here is my admin login and logout controller:

public function enter(AdminLogin $admin){
        $credentials = $admin->only(['email', 'password']);
        if(Auth::guard('admin')->attempt($credentials)):
            $admin = ModelsAdmin::whereEmail($admin->email)->first();
            Auth::login($admin);
            return redirect()->route('dashboard.show');
        endif;

        return redirect()->back()->withMsg("There is A worng in your Credentials");
    }

    public function logout(){
        auth('admin')->logout();

        return redirect()->route('admin.login');
    }

And here is my user login and logout:

public function enter(UserCheck $user){
    $credentials = $user->only(['email', 'password']);
    if(Auth::guard('user')->attempt($credentials)):
        $login = ModelsUser::whereEmail($user->email)->first();
        Auth::login($login);
        return redirect()->route('user.dashboard');
    endif;
    return back()->withMsg('Sorry sir you Entered invalid Credentials');
}
public function logout(Request $request){

    Auth::guard('user')->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return redirect()->route('user.login');
}
1 Answers

the problem was in the admin middleware . i made check for admin by auth()->check() it should be auth('admin')->check() because there are another middleware for user is default so the two confilicted

Related