Laravel 5.2:如何在中间件中使用auth

时间:2016-01-15 06:57:43

标签: php authentication laravel-5 middleware laravel-5.2

我已经创建了一个新的中间件名称Adminpanel

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Adminpanel
{
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role == 'admin'){
            return $next($request);
        }else{
            return redirect('admin/login');
        }
    }
}

并注册中间件

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'adminpanel' => \App\Http\Middleware\Adminpanel::class,
];

和路线

Route::group(['middleware' => ['web','adminpanel']], function () {
Route::get('/admin/dashboard/', 'admin\Dashboard@index');
//

});

但是当我运行时,它问我试图获取非对象的属性,意味着我无法在这里访问Auth类,有人可以告诉我错误是什么以及如何在中间件中访问Auth Facade。

这是我的身份验证码

public function authenticate(Request $request)
{
    if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'), 'role' => 'admin'], $request->input('remember'))) 
    {
        return redirect()->intended('admin/dashboard');
    }
    else{
        return redirect('admin')->with('response',-1);
    }
}

由于

1 个答案:

答案 0 :(得分:3)

这并不意味着您无法访问 Auth 课程。这意味着,该用户未经过身份验证, Auth :: user()返回 NULL

确保只有经过身份验证的用户才能使用 auth 中间件访问您的路由,或首先检查用户是否经过身份验证:

if(Auth::check() && Auth::user()->role == 'admin'){
  return $next($request);
} else {
  return redirect('admin/login');
}