we have an application in laravel and have a route:
Route::get('/example-route', "exampleController@index")->middleware("example_middleware");
i want to get http status code of this request in middleware . how can i do it?
I mean blue part that selected in this image
Advertisement
Answer
You can’t get the status code inside the middleware because it doesn’t exist yet.
The status code is part of the response, not the request, therefore it’s not “available” in a middleware.
The 200
you see is the code returned by your application:
- Laravel receives a request to
/example-route
- All required middlewares handle the request one after another
- The route finally hits the controller:
exampleController@index
- The
index
method in the controller returns a status code: this is the status code highlighted in blue in your screenshot.
public function index() { return response('This is a code 200', 200); //returns 200 return response('This is a code 400', 400); //returns 400 // and so on... }
By default, if there is no error, Laravel sends a 200
and as you probably know, a 500
is the generic error code when there is a server error.
The full list of HTTP status codes can be found here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Again, since this code is what you return (or what Laravel returns depending of the request outcome), it can’t be “accessed” in the middleware since it doesn’t event exist at this point.
I want to have status code (for requested url) in user activity logs
If you want to log the status code, you’ll have to log it right before the response is sent.
public function index() { // the logs should be created here return response('This is a code 200', 200); //returns 200 }