简体   繁体   中英

Laravel - Return json along with http status code

If I return an object:

return Response::json([
    'hello' => $value
]);

the status code will be 200. How can I change it to 201, with a message and send it with the json object?.

I don't know if there is a way to just set the status code in Laravel.

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

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); 

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;

There are multiple ways

return \Response::json(['hello' => $value], STATUS_CODE);

return response()->json(['hello' => $value], STATUS_CODE);

where STATUS_CODE is your HTTP status code you want to send. Both are identical.

if you are using Eloquent model, then simple return will also be by default like, ,例如,

return User::all();

laravel 7.* 您不必指定 JSON RESPONSE因为它会自动将其转换为JSON

return response(['Message'=>'Wrong Credintals'], 400);
return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

希望我的回答有帮助。

It's better to do it with helper functions rather than Facades . This solution will work well from Laravel 5.7 onwards

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

我自己更喜欢响应助手:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);
return response('Your text.', 422);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM