Search code examples
phplaravelauthenticationmiddlewareroles

Laravel 10 Auth::user() - Attempt to read property on null


All i am trying to do is make a middleware where only user with role_id = 1 can access the dashboard.

Now keep in mind i didn't use laravel/breeze, instead i used laravel/ui auth

Here is my checkRole middleware:

public function handle(Request $request, Closure $next): Response
{
    if(Auth::user()->role_id != 1)
    {
        return redirect()->route("welcomepage");
    } 

    return $next($request);

}

Here is the middleware in web.php :

Route::middleware(["checkRole"])->group(function() {
    Auth::routes(["register" => false, "reset" => false]);
    //I use these parameters because i don't want these routes
});

I have used the same middleware before with laravel/breeze and had no problem but now with laravel/ui auth i get this error.


Solution

  • While i was typing the question i randomly came with the solution. laravel/ui auth in the HomeController.php in the constructor method are the middlewares listed

    This is how it looks now:

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('checkRole'); //just added it
    }
    

    And in web.php i just removed the middleware and have only:

    Auth::routes(["register" => false, "reset" => false]);
    

    The middleware method stays the same.