laravel 在中间件中使用 Auth::user

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29785932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:24:55  来源:igfitidea点击:

Using Auth::user in middleware

laravellaravel-middleware

提问by Michael N

I'm trying to check if the URL entered is the same as the authenticated users slug in the database. So if a user goes to example.com/user/bob-smith and it is in fact Bob Smith logged in, the application will let Bob continue because his slug in the User table is bob-smith.

我正在尝试检查输入的 URL 是否与数据库中经过身份验证的用户 slug 相同。因此,如果用户访问 example.com/user/bob-smith 并且实际上是 Bob Smith 登录,则应用程序将让 Bob 继续,因为他在 User 表中的 slug 是 bob-smith。

I have the middleware registered but when I do

我已经注册了中间件,但是当我注册时

public function handle($request, Closure $next)
    {
        if($id != Auth::user()->slug){
            return 'This is not your page';
        }
        else{
            return $next($request);
        }
    }

I get

我得到

Class 'App\Http\Middleware\Auth' not found

找不到类“App\Http\Middleware\Auth”

I'm not sure how to use this inside of middleware. Can any one help?

我不确定如何在中间件内部使用它。任何人都可以帮忙吗?

回答by peterm

It's quite easy. It looks like you didn't import the namespace for Authfacade.

这很容易。看起来您没有为Auth外观导入命名空间。

Therefore either add

因此要么添加

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth; // <- import the namespace

class YourMiddleware {
    ...
}

above the class declaration or use a fully qualified class name inline

在类声明之上或使用完全限定的类名内联

if ($id != \Illuminate\Support\Facades\Auth::user()->slug) { 


Alternatively you can inject Guardinstance in the constructor

或者,您可以Guard在构造函数中注入实例

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class YourMiddleware {

    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next) 
    {
        ...
        if ($id != $this->auth->user()->slug) {
        ...
    }
}