119

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
Galivan
  • 4,842
  • 9
  • 44
  • 76

10 Answers10

147

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
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 3
    Keep in mind that **Symfony\Component\HttpFoundation\Response** has its own predefined constants for http status codes, and if you use other than that it will change your status into something close to it... i.e. if you want to set status **449**, you will always get status **500** – Mladen Janjetovic Nov 05 '15 at 23:11
  • 2
    @Tushar what if I don't want to send any data back, just a 200 response? Is `response()->json([], 200);` fit for purpose in this situation? Or is 200 implicit? – Jonathan Jul 05 '16 at 10:43
  • + (201) this answer safes my evening :) – Maytham Fahmi Oct 23 '16 at 00:29
  • 1
    `use Illuminate\Http\Response;` and `return new Response(['message' => 'test'], 422);` worked for me – Derk Jan Speelman Oct 13 '20 at 11:48
89

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); 
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
Jeremy C.
  • 2,405
  • 1
  • 12
  • 28
  • 1
    @timeNomad What are the pros and cons of these two methods - which is recommended? – DJC Apr 28 '16 at 11:46
  • 2
    @DJC on first method you will be able to use Response:: several times loading only once. On second method you will call that class to each time you use response()-> (no problem if you'll use only one). – Marcelo Agimóvel Apr 07 '18 at 20:56
48

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;
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
TKoutsou
  • 481
  • 4
  • 2
  • Thanks, I was looking for a reference to this. Do you happen to have a link to the other available response names such as 201, 400 etc and not just the 200 (HTTP_OK)? I've tried googling it but haven't been able to find it quite yet! – jjmu15 May 19 '20 at 08:45
  • 1
    Nevermind... found it. Here is a complete list for anyone else who may be looking for it: https://gist.github.com/jeffochoa/a162fc4381d69a2d862dafa61cda0798 – jjmu15 May 19 '20 at 08:50
15

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();
Nico Burns
  • 16,639
  • 10
  • 40
  • 54
iSensical
  • 747
  • 5
  • 8
6

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

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

Hope my answer was helpful.

Mikayel Margaryan
  • 764
  • 1
  • 7
  • 16
2

I always use this type of json response format, this will help you...

return response()->json(['success'=>'true','message' => 'Successfully Done.'], 200);
1

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

I prefer the response helper myself:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);
Dylan Pierce
  • 4,313
  • 3
  • 35
  • 45
-1
use Symfony\Component\HttpFoundation\Response;

  return response()->json([
            'message' => 'success',
            'status' => Response::HTTP_OK
        ]);
  • 1
    While this code snippet may be the solution, including a detailed explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Shawn Hemelstrand Feb 26 '23 at 01:36