Home » Php » php – How can I get exact user plus the user's exact posts in laravel from jwt token laravel

php – How can I get exact user plus the user's exact posts in laravel from jwt token laravel

Posted by: admin February 25, 2020 Leave a comment


I’m trying to get a list of a single user plus his/her post in another table, while passing the user jwt token in the header.

public function getAuthenticatedUser()
    try {

        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent'], $e->getStatusCode());


    // the token is valid and we have found the user via the sub claim

    $user = auth()->user();
    $userid = User::where('id', $user->id);
    $return = UserResource::collection($userid);   
    return response()->json($return);


While doing it this way I get

BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Builder::mapInto() in file C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 50

#0 C:\xampp\htdocs\doc\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php(36): Illuminate\Database\Eloquent\Builder::throwBadMethodCallException('mapInto')

But if I do it this way;

$user = auth()->user();
$userid = User::find($user);
$return = UserResource::collection($userid);   
return response()->json($return);

I get a response, but I get two users returned, instead of the exact user with the jwt token

When I return just auth()->user() I get the exact user of the jwt but without the post resource.

How can I get exact user plus the user’s exact posts

How to&Answers:

I see a problem in the following snippet.

User::where('id', $user->id);

where is a syntactic sugar for calling where on a query builder, it therefor returns a query builder, to retrieve the user this way.

User::where('id', $user->id)->first();

Secondly a helper is made for this exact case called find(), you can call statically on model classes.

$user = User::find($user->id);


$return = UserResource::collection($userid);

Expects a Collection, therefor change it to a single resource.

$return = new UserResource($userid);