【问题标题】:Using Auth::user in middleware在中间件中使用 Auth::user
【发布时间】:2015-06-29 10:11:01
【问题描述】:

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

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

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

我明白了

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

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

【问题讨论】:

    标签: laravel laravel-middleware


    【解决方案1】:

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

    因此要么添加

    <?php namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth; // <- import the namespace
    
    class YourMiddleware {
        ...
    }
    

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

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

    您也可以在构造函数中注入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) {
            ...
        }
    }
    

    【讨论】:

    • Doh,我现在觉得有点傻,但这行得通。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2016-12-08
    • 2021-07-25
    • 2023-03-18
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多