Laravel - Return json along with http status code

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

提交回复
热议问题