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?