首页 > 解决方案 > 在 laravel 中自定义守卫尝试方法

问题描述

我想为来自同一个表但角色不同的用户实现多重身份验证。我的目标是,如果用户正在从手机查看,系统搜索角色 = 用户的用户对象,如果它来自 pc,系统搜索角色 = 管理员的用户对象。

为此,我在 config/auth.php 中添加了 2 个自定义保护:

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

我还将逻辑添加到 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')
            );
        }
    }

我还尝试修改 AuthServiceProvider boot() 方法中的守卫:

        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();
        });

我的问题是如何覆盖警卫的尝试方法,以便它使用我需要的逻辑?我错过了什么,我还应该定义什么?

我在这种状态下收到的当前错误:

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

先感谢您

标签: phplaravelauthenticationrolesguard

解决方案


推荐阅读