Using Auth::user in middleware

user1871245 picture user1871245 · Apr 22, 2015 · Viewed 10.2k times · Source

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?

Answer

peterm picture peterm · Apr 22, 2015

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