[英]How can I get exact user plus the user's exact posts in laravel from jwt token
[英]How can I get exact user plus the user's exact posts in laravel from jwt token laravel
我試圖在另一個表中獲取單個用戶及其帖子的列表,同時在標題中傳遞用戶 jwt 令牌。
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);
}
雖然這樣做我得到
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')
但如果我這樣做;
$user = auth()->user();
$userid = User::find($user);
$return = UserResource::collection($userid);
return response()->json($return);
我收到了響應,但返回了兩個用戶,而不是具有 jwt 令牌的確切用戶
當我只返回auth()->user() 時,我得到了 jwt 的確切用戶,但沒有 post 資源。
如何獲得確切的用戶以及用戶的確切帖子
我在以下代碼段中看到了一個問題。
User::where('id', $user->id);
where 是用於在查詢構建器上調用 where 的語法糖,因此它返回一個查詢構建器,以這種方式檢索用戶。
User::where('id', $user->id)->first();
其次,為這種稱為 find() 的確切情況制作了一個幫助程序,您可以在模型類上靜態調用。
$user = User::find($user->id);
編輯
$return = UserResource::collection($userid);
需要一個集合,因此將其更改為單個資源。
$return = new UserResource($userid);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.