Laravel - Return json along with http status code
You can use http_response_code()
to set HTTP response code.
If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.
http_response_code(201); // Set response status code to 201
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here
I think it is better practice to keep your response under single control and for this reason I found out the most official solution.
response()->json([...])
->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
add this after namespace
declaration:
use Illuminate\Http\Response;
This is how I do it in Laravel 5
return Response::json(['hello' => $value],201);
Or using a helper function:
return response()->json(['hello' => $value], 201);