Laravel后卫不工作

时间:2017-09-25 23:22:35

标签: php

我尝试使用laravel 5.5实现管理员/用户登录。我创建了Admin模型,与用户模型完全相同,并为admin设置了防护。但在登录期间,警卫没有被传递:

这是我的AdminController:

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;


class AdminController extends Controller{
    use AuthenticatesUsers;

    protected $guard = 'admin';

    public function showLoginForm(){
        return view('admin')->with(['title' => 'Panel de Administrador - Iniciar Sesión', 'bodyClass' => 'admin-view']);
    }
}

我尝试调试,然后进入vendor文件夹,访问AuthenticatesUsers类,并调试请求:

enter image description here

如您所见,它使用的是用户模型和网络防护。这里是关于警卫的配置文件:

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

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

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

然后我有提供者:

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

1 个答案:

答案 0 :(得分:0)

没关系我弄清楚了。 Guard不是类的属性,它是一个函数,所以我必须替换继承的guard函数,并使用Auth facade,如下所示:

use Illuminate\Support\Facades\Auth;

class AdminController extends Controller{
    use AuthenticatesUsers;

    public function guard(){
        return Auth::guard('admin');
    }

    public function showLoginForm(){
        return view('admin')->with(['title' => 'Panel de Administrador - Iniciar Sesión', 'bodyClass' => 'admin-view']);
    }
}