Laravel 5.7 Guard和中间件无法正常工作

时间:2019-02-01 22:38:12

标签: laravel laravel-5

在我的Laravel实例中,后卫或中间件无法正常工作。我的管理面板始终显示为auth或non-auth。我不明白问题是什么。

路线

Route::get('/admin', 'admin\adminController@index')->middleware('auth:admin');
Route::get('/admin-login', 'auth\adminLoginController@index');
Route::post('/admin-login', 'auth\adminLoginController@login')->name('admin.login.submit');

控制器

<?php

namespace App\Http\Controllers\auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;

class adminLoginController extends Controller
{
    function __construct()
    {
        $this->middleware('guest:admin');
    }

    public function index()
    {
        return view('auth.admin-login');
    }

    public function login(Request $request)
    {
        $this->Validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);

        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], false, false)) {
            return redirect('/admin');
        }

        return redirect()->back()->with('message', 'Invalid Information');
    }
}

如果我删除__construct(),那么我可以访问管理员登录页面,否则我不能进入!!

我的auth.php代码:


守卫:

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

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

    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],

],

提供商

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

    'admins' => [
        'driver' => 'eloquent',
        'model' => App\admin::class,
    ],
],

adminController

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;

class adminController extends Controller
{
    public function index()
    {
        $user = User::all();
        $maleuser = User::where('gender', 'male')->get();
        $femaleuser = User::where('gender', 'female')->get();
        return view('admin/index')
            ->with('users', $user)
            ->with('maleusers', $maleuser)
            ->with('femaleusers', $femaleuser);
    }
}

1 个答案:

答案 0 :(得分:0)

修改路线,看起来像这样

Route::get('/admin', 'admin\adminController@index')->middleware('auth:admin');
Route::get('/admin-login', 'auth\adminLoginController@index')->middleware('guest:admin');
Route::post('/admin-login', 'auth\adminLoginController@login')->name('admin.login.submit')->middleware('guest:admin');

还要在您的adminLoginController中编辑此行

function __construct()
{
    $this->middleware('guest:admin')->except('logout');
}