niilante
niilante

Reputation: 568

Laravel, How to get the current HTTP status code in blade view error page eg. 404.blade.php

I have generated error pages using Laravel's php artisan vendor:publish --tag=laravel-errors command.

Now inside, let's say 404.blade.php view, I want to get the status code of 404 and use it for a simple if-else case but I don't want to include any tag around and later getting the variable, so I tried below

http_response_code() and app('Illuminate\Http\Response')->status()

But ironically, both sometimes return 200 as the http response code while I'm expecting to get 404.

What's the problem?

Upvotes: 3

Views: 3158

Answers (1)

niilante
niilante

Reputation: 568

As an instance of HttpException being passed to the custom 404 blade page.

The view could use the $exception variable that has been predefined by Laravel, to get http status code.

So if you leverage on this code $exception->getStatusCode() you will return 404.

Also, if you try this approach for any other error page you'll get the response code of the page.

NB: This was tested in Laravel 7.X

Upvotes: 6

Related Questions