Manzoor-Bajwa's avatar

Laravel 5.1 Custom HTTP Status Code and Status Text

Hi I'm working with RESTful web services. I want to return custom HTTP header status code and status text instead of default. For example if everything is OK then it returns 200 OK.

But what i want is to customize like so 401 You need to login again.

How do i do that?

Thanks

0 likes
8 replies
Manzoor-Bajwa's avatar

Thanks @krballard94 , but I'm still getting same status text. Like you mentioned above

response('You need to login again.', 401);

line does the same. I am getting the message in response body.

2serve's avatar

Did you find a solution? Having the same problem...

usman's avatar
usman
Best Answer
Level 27

@2serve use:

//example
return response()->setStatusCode(201, 'The resource is created successfully!');

Usman.

2 likes
2serve's avatar

Hi Usman,

i get a 'Method setStatusCode does not exist.' error using your code.

You pushed me in the good direction, thanks.

the following works but a one-liner would be great..

use Illuminate\Http\Response;
...
$response = new Response();
return $response->setStatusCode(201, 'The resource is created successfully!');

Nice Regards, Kristof

3 likes
oldtimeguitarguy's avatar

@2serve - thank you for this. Here's your one-liner:

return (new \Illuminate\Http\Response)->setStatusCode(201, 'The resource is created successfully!');
mazedul's avatar

Some alternative:

  1. response('The resource is created successfully, 200);
  2. response()->json(['status' => 'The resource is created successfully'], 200);
amitshahc's avatar

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;`
    

Below is also not returning 200 ok:

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

Please or to participate in this conversation.