lulli240
4 years ago
10246
20
Laravel

How can I access the Auth::user() in a middleware class?

Posted 4 years ago by lulli240

I'm trying to check if user has access to a certain page using a middleware class

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AdminMiddleware
{
    public function handle($request, Closure $next)
    {
        if(!Auth::check()){
            return redirect('/');
        }
        
        if(!Auth::user()->access){
            return redirect('dashboard');
        }

        return $next($request);
    }
}

But the Auth::user() is a null so I get the "Trying to get property of non-object" error.

I have been on google for hours trying out others people ideas but none of them seem to be working.

Is there a way or entirely different way og doing this?

Please sign in or create an account to participate in this conversation.