2

Laravel version: 5.5

I am trying to return custom http status code from the laravel controller. (Calling this url using jQuery Ajax $.get())

In my controller function I tried both the way mentioned bellow but it's not working.

  1. This one returns error "Method setStatusCode does not exist."

    return response()->setStatusCode(202);
    
  2. This one not throwing error but returning 200 always.

    $response = new Response();
    $response->setStatusCode(202);
    $response->header('custom', 555);
    return $response;`
    

3 Answers 3

5

Use it like this:

return response()->json("response content", 202);
//or
return response()->make("response content", 202);

Check https://laravel.com/api/5.0/Illuminate/Routing/ResponseFactory.html for more detailed documentation.

Sign up to request clarification or add additional context in comments.

4 Comments

I still wonders why not working. btw i am calling the http request from jQuery ajax. is there something to do with it?
response() function returns a response FACTORY not a response instance, so setStatusCode is not defined in a factory class. You need to create a response instance to set a status code. make and json functions do that. And second option that you used fails probably because you are not using Symfony\Component\HttpFoundation\Response class but some other Response class.
I was using use Illuminate\Http\Response; now using use Symfony\Component\HttpFoundation\Response; still returning the 200 with #2.
Guess what? i should delete this thread. all of your codes working. the reason was i was calling a internal function withing the controller public function and returning from the 2nd one. now i updated the code to return from the 2nd and the caller public function. it works. sorry. but this was not the issue so deleting it.
1

You can use return response()->json(['hello' => $value],201);

4 Comments

using use Illuminate\Http\Response; returns message Method json does not exist.
response()->json() should do it
Guess what? i should delete this thread. all of your codes working. the reason was i was calling a internal function withing the controller public function and returning from the 2nd one. now i updated the code to return from the 2nd and the caller public function. it works. sorry. but this was not the issue so deleting it.
Do not delete the question, it could be useful to people having the same issue :-)
0

Let me present a few more methods of use. Maybe you are looking for something like this without json.

response(null)->setStatusCode(202);
response(null, 202);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.