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
Take a look here:
abort(401, 'You need to login again.');
// or
response('You need to login again.', 401);
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.
Did you find a solution? Having the same problem...
@2serve use:
//example
return response()->setStatusCode(201, 'The resource is created successfully!');
Usman.
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
@2serve - thank you for this. Here's your one-liner:
return (new \Illuminate\Http\Response)->setStatusCode(201, 'The resource is created successfully!');
Some alternative:
response('The resource is created successfully, 200);
response()->json(['status' => 'The resource is created successfully'], 200);
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.
This one returns error "Method setStatusCode does not exist."
return response()->setStatusCode(202);
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 sign in or create an account to participate in this conversation.