0

I have a route that looks like the following my routes/api.php file for a Laravel 8 project:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    Log::debug("request user: {$request->user()}");
    return ['data' => $request->user()];
});

In my log file, I clearly see $request->user() returning an authenticated user. Meaning, $request->user() is not null and has an Eloquent object coming back from the database.

The body of my response, however, says otherwise:

{
    "data": {}
}

Is there some gotchya in Laravel 8 that I'm overlooking? Why is the value for data an empty object when $request->user() contains an authenticated user?

The output from the log is a standard user object:

{"id":46,"name":"Amanada Name","family_name":"Name","given_name":"Amanda","phone_number":null,"email":"foo@bar.net","sub":"facebook|12341234121","remember_token":null,"created_at":"2021-01-02 23:46:00","updated_at":"2021-01-02 23:46:00"}
randombits
  • 47,058
  • 76
  • 251
  • 433

1 Answers1

0

Solution found: PHP json_encode class private members)

The problem is json_encode, which Laravel uses underneath the hood when converting the PHP Array to JSON, does not encode the class members. I created a User Resource and updated the route to return the following:

return response()->json(['data' => new UserResource($request->user())], 200);

Dharman
  • 30,962
  • 25
  • 85
  • 135
randombits
  • 47,058
  • 76
  • 251
  • 433
  • Api resources are always good choice to be made. Good practice regarding laravel can be found [here](https://github.com/alexeymezenin/laravel-best-practices). – Tpojka Jan 03 '21 at 15:12