I'm creating an API for a blog using Laravel and in my UserController, for some routes, I get the currently authenticated user as seen below:
public function getUser() {
$user = auth()->user();
return response()->json($user, 200);
}
This returns a json object of the user. I get the user in other functions in the same way. I wanted to move this line into a wider scope so I could access it in all functions so I placed it in the constructor:
class UserController extends Controller {
protected $user;
public function __construct() {
$this->user = auth()->user();
}
}
I refactored getUser to look like this;
public function getUser() {
return response()->json($this->user, 200);
}
Now it just returns an empty object and the 200 status code. Why does making it a class property no longer return the object?
The session middleware has not ran yet; the Controller is instantiated before the Request goes through the middleware stack, so you won't have access to session based authentication at that point (so auth()->user()
would be null
). You can use a Controller middleware to do this though:
class UserController extends Controller
{
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = $request->user();
return $next($request);
});
}
}
This middleware will run after the other middleware in the stack so you will have access to the session at that point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With