Using Auth :: user in middleware

I am trying to check if the entered URL matches missed users in the database. Therefore, if the user goes to example.com/user/bob-smith and Bob Smith is actually logged in, the application will let Bob continue because his slug in the User table is bob-smith.

I have registered middleware, 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 am not sure how to use this inside middleware. Can anyone help?

+4
source share
1 answer

. , Auth.

<?php namespace App\Http\Middleware;

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

class YourMiddleware {
    ...
}

inline

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

All Articles