Using Auth::user in middleware

霸气de小男生 提交于 2019-12-10 14:04:26

问题


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.

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

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


回答1:


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

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 Guard instance in the constructor

<?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) {
        ...
    }
}


来源:https://stackoverflow.com/questions/29785932/using-authuser-in-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!