Customizing guard attempt method in laravel

Viewed 639

I want to implement multiple authentication for users from the same table, but with different roles. My goal would be, if the user is viewing from mobilephone, the system searches the User object where role = user, and if it is coming from pc, the system searches the User object where role = admin.

For this I added 2 custom guards, in to the config/auth.php:

       'admin' => [
            'driver' => 'custom-admin',
            'provider' => 'users',
        ],
        'user' => [
            'driver' => 'custom-user',
            'provider' => 'users',
        ],

And I also added the logic into the LoginController

    protected function attemptLogin(Request $request)
    {
        $is_mobile = (isset($request->is_mobile) && $request->is_mobile == 'true') ? true : false;
        if($is_mobile == true)
        {
            return $this->guard('user')->attempt(
                $this->credentials($request), $request->filled('remember')
            );
        }
        else
        {
            return $this->guard('admin')->attempt(
                $this->credentials($request), $request->filled('remember')
            );
        }
    }

and I also tried to modify the guards in the AuthServiceProvider boot() method:

        Auth::viaRequest('custom-admin', function ($request) {
            return User::where('email', $request->email)->where('password', Hash::make($request->password))->where('role', 'admin')->first();
        });

        Auth::viaRequest('custom-user', function ($request) {
            return User::where('email', $request->email)->where('password', Hash::make($request->password))->where('role', 'user')->first();
        });

My question would be how can I override the guard's attempt method so it is using the logic I need? What do I miss, what else should I define?

The current error what I receive in this state:

Method Illuminate\Auth\RequestGuard::attempt does not exist.

Thank you in advance

0 Answers
Related