Onez Kahazevez Onez Kahazevez - 28 days ago 14
PHP Question

How To Retrieve Authenticated User Inside routes.php On Laravel 5.3

I try to access current authenticated user on routes.php, but it return null value whereas if I try to access it in a controller, the value returned normal.

dd(Auth::guard('admin'))->user()->name);


or with

dd(auth()->guard('admin'))->user()->name);


So what the best way to retrieve a current authenticated user in routes file. The purpose is simply to let's load and register some protected route only when user get logged in. The public access no need almost that route. Also this will be used to only register some services if user logged in.

Answer

You can't, because when Laravel processes routes files auth object is not created yet, so you'll get null if you'll just put something like auth()->user() in routes file.

Comments