Handy methods for unauthorized and forbidden responses in Laravel 8.x
Working with Laravel’s HTTP client, there might be the scenario where the outgoing HTTP requests that you’re making might return responses with different status codes.
Among all the HTTP response codes, two response codes are sent when the user is not authorized to access the resources for two different reasons.
-
401 Unauthorized — The status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.
-
403 Forbidden — The status code indicates that the server understands the request but refuses to authorize it. Meaning the access is permanently forbidden and tied to the application logic, such as insufficient rights to a resource.
The old way
Now, the Laravel HTTP client lets you check these status codes through the status()
method that you can call on the HTTP response like so.
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
if ($response->status() === 401) {
//
}
if ($response->status() === 403) {
//
}
Convenient methods
This is good but with the recent release of Laravel 8.x, the framework comes with two convenient methods to check this all at once.
if ($response->unauthorized()) {
//
}
if ($response->forbidden()) {
//
}
As you can tell, this is pretty handy and more recognizable. Less mental mapping is always good!
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.