0

My question is simple : Is it possible to set the http response code before the controller method return (if I return a php table, for json response).

I know that it's possible to do that :

return response()->json($json,HTTP_CODE);

But I want something to set the code somewhere in the controller without modifying the final return. Or do you know a way to make the native php function http_response_code working ? Because Laravel overwrite it during building the Response. Is it possible ? Or you have to do it in the return ?

I want to know if it is possible to do that or not :

 public function myMethod(){
    //Some code
     $this->injectHttpCode(400); //or how to use native native http_response_code(400); ?
    //Some code
    return $this->json; //I dont want to modify that
 }

I dont want any "return" in you answer, just tell me if it's not possible.

1

2 Answers 2

1

If you want to have some sort of standard way to handle the response code, the easiest way to do is to have a base BaseController that contains this:

protected function getResponseStatusCode() : int
{
    switch (request()->getMethod()) {
        case 'GET':
        case 'PUT':
            return 200;
        case 'POST':
            return 201;
        case 'DELETE':
            return 204;
        default:
            return request()->getMethod();
    }
}

And:

public function respond($json) 
{
    return response()->json($json, $this->getResponseStatusCode());
}

so in your controller you only call the method in the base controller with:

return $this->respond($json);
Sign up to request clarification or add additional context in comments.

1 Comment

I know that, please read my question "But I want something to set the code somewhere in the controller without modifying the final return" I have edited my question with an example that I want to do.
0

How about using response() function to do something like this:

public function myMethod(){
    $response = response();

    //Some code
     $response->setStatusCode(400);

    return $response->json([]);
 }

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.