Home > database >  Retrieving Authenticated User with relation data laravel 8
Retrieving Authenticated User with relation data laravel 8

Time:02-10

I'm currently studying about JWT auth on laravel 8. To explain what im trying to do straightforwardly, im trying to send the user data with the relations data when successfully authenticated. please take a look on my code bellow

    //response login "success" with generate "Token"
    return response()->json([
        'success' => true,
        'user'    => auth()->guard('api')->user(),  
        'token'   => $token
    ], 200);enter code here

in this case the api return auth condition with user data and jwt token. but 'user' => auth()->guard('api')->user() not returning the user data with the relation data. currently my users table has a relation with roles table so i also want to send the role data based on role id in users data. something like eager loading using with() function. if you have any clue or solution about this please help me to resolve this problems. Thankyou

CodePudding user response:

You could utilize the lazy loading methods for Laravel Models

https://laravel.com/docs/8.x/eloquent-relationships#lazy-eager-loading

$user = auth()->guard('api')->user();

$user->load(['relation1', 'relation2']);

return response()->json([
        'success' => true,
        'user'    => $user,  
        'token'   => $token
    ], 200);

Or you could potentionally ALWAYS load the relationships for the User model by adding them to the Model

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-by-default

class User extends ExtendedClasses
{
    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['relation1', 'relation2'];
  • Related