I want to access the auth()->user()-> in routs like web.php?

Viewed 276

How can I access the user role from auth in web.php please can anyone provide the method to access the user in web.php?

Trying this code

dd(Auth::check(),auth()->user());

I am logged in and also have authenticated user but showing this output

enter image description here

1 Answers

You can use the Auth facade, but as pointed out in the comments it needs to be inside middleware or a route handler, otherwise it won't be properly initialised yet.

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

Auth::user(); //here Auth functions fail

Route::get('/', function () {
    if (Auth::guest()) {   //but here it will work
        return redirect('/login');
    } else {
        return redirect('/dashboard');
    }
});
Related