So many time we need to return in REST APIs the request body. For example if you send a POST request with some parameters and you wanted you API access token along with the request body parameters which you sent.
Like below example:
Here is the Request body:
1 2 3 4 5 6 7 8 |
{ "name":"Coding 4 Developers", "email":"info@coding4developers.com", "password" : "654321123", "role" : 2, "deviceId" : "TestDeviceId", "deviceType" : 1 } |
And now you wanted to get register and access token in response along with above request body like below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "status": 1, "message": "You have been registered successfully.", "errors": [], "data": { "name": "Coding 4 Developers", "email": "info@coding4developers.com", "password": "654321123", "role": 2, "deviceId": "TestDeviceId", "deviceType": 1, "accessToken": "81962729efe37e293bda6571eb64bfa0" // access token a new added key in request body } } |
How can we do this in Laravel????
Here is the answer of this question. You can get the HTTP request body in Laravel by following code:
1 |
$request->all() |
Now if you wanted to send the request body with along with access token in JSON response in Laravel, You can do it like following example:
1 |
array_merge($request->all(), ['accessToken' => $accessToken]) |
So finally function to return the JSON response after registration of the user looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static function registerUser($request) { UserServiceProvider::$data['message'] = trans('messages.server_error'); try { $userId = User::create($request); $accessToken = md5(uniqid(mt_rand(), true)); $isAccessTokenCreated = AccessToken::create($request, $accessToken, $userId); if ($userId && $isAccessTokenCreated) { UserServiceProvider::$data['status'] = 1; UserServiceProvider::$data['data'] = array_merge($request->all(), ['accessToken' => $accessToken]); // here merging the access token in request body UserServiceProvider::$data['message'] = trans('messages.user_registered'); } } catch (\Exception $e) { Log::error( __CLASS__ ."::" . __METHOD__ . " " . $e->getMessage()); } return UserServiceProvider::$data; } |
Good Friend,
your all examples are very good.
Deepak K.