Laravel - Return json along with http status code

后端 未结 8 1868
北恋
北恋 2020-12-08 03:57

If I return an object:

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

the status code will be 200. How can I change it to 201, with

相关标签:
8条回答
  • 2020-12-08 04:06
    return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity
    

    Hope my answer was helpful.

    0 讨论(0)
  • 2020-12-08 04:13

    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
    
    0 讨论(0)
  • 2020-12-08 04:14

    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;
    
    0 讨论(0)
  • 2020-12-08 04:15

    I prefer the response helper myself:

        return response()->json(['message' => 'Yup. This request succeeded.'], 200);
    
    0 讨论(0)
  • 2020-12-08 04:17

    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
    
    0 讨论(0)
  • 2020-12-08 04:22

    laravel 7.* You don't have to speicify JSON RESPONSE cause it's automatically converted it to JSON

    return response(['Message'=>'Wrong Credintals'], 400);
    
    0 讨论(0)
提交回复
热议问题