Laravel - Return json along with http status code

后端 未结 8 1869
北恋
北恋 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:23

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

    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 auto converted in JSON by default like,

    return User::all();
    
    0 讨论(0)
提交回复
热议问题