I am creating API with Laravel 5.2 and Dingo API package. When a user is created, I want to return 201
response with the new $user->id
.
My Code
return $this->response->created();
As per Dingo documentatio, I can provide a location
and $content
as parameters in the created()
function.
My question is, what location information I need to return here and I tried to set my new user as $content
, but it's not working or I am not sure what to expect.
Can someone please explain this created()
function?
What this does is set the Location
header, as seen in the source:
/**
* Respond with a created response and associate a location if provided.
*
* @param null|string $location
*
* @return \Dingo\Api\Http\Response
*/
public function created($location = null, $content = null)
{
$response = new Response($content);
$response->setStatusCode(201);
if (! is_null($location)) {
$response->header('Location', $location);
}
return $response;
}
So, in your example since you're creating a new user, you might send the users profile page as the location, something like:
return $this->response->created('/users/123');
As for the content, as you can see in the function this sets the content on the return. In your case, it would probably be a json string with the new user information, something like:
return $this->response->created('/users/123', $user); // laravel should automatically json_encode the user object