'api response laravel doesn't show

I have some problem when I want to return a value from api, when I use dd() function it will show the result. But when I use return, it doesn't show the result

Route::middleware('auth:api')->get('/user', function (Request $request) {
    dd($request->user()); 
});

when use dd()

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return response()->json($request->user());
});

nothing to show

Any ideas how to show it?



Solution 1:[1]

That is because you are returning a GenericUser, Illuminate\Auth\GenericUser, not an Eloquent Model; you are not using an Eloquent Model for the User Provider your Guard is using. This class doesn't have any means to serialize this object to JSON like a Model does and doesn't have any public properties that json_encode could serialize.

If you json_encode this object you get an empty object in JSON notation:

echo json_encode(new Illuminate\Auth\GenericUser(['id' => 1]));

// {}

Perhaps you want to be using an Eloquent Model such as App\User for authentication?

config/auth.php

$providers = [
    ...
    'users' => [
        'dirver' => 'eloquent',
        'model' => App\User::class,
    ],
];

You are currently using the 'database' driver for your 'users' provider so you get a GenericUser to represent your user.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1