因此,我尝试通过登录请求返回User
数据。我正在使用食肉,但我不知道如何将数据附加到响应中。
这是登录方法
public function login(Request $request)
{
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
我想做这样的事情
$user = User::where('email', $request->username)->get();
$token = $response->getBody();
return response()->json($token, $user);
但是,当我尝试此操作时,出现错误。任何帮助将不胜感激。当前,我必须在访问令牌之后单独发出请求以返回用户数据,因此我希望它同时发生。...
答案 0 :(得分:0)
json方法的第一个参数可以是一个数组:
return response()->json(['token' => $token, 'user' => $user ]);
答案 1 :(得分:0)
我被推荐以下discussion,它解决了我的问题。这是最终代码
public function login(Request $request)
{
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
$token = $response->getBody();
$data = json_decode($token, true);
$user = User::where('email', $request->username)->with('role.rules')->get();
$rules = $user->pluck('role')->collapse()->pluck('rules');
$rules->put('access_token', $data['access_token']);
return response()->json($rules);
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}