Handy methods for unauthorized and forbidden responses in Laravel 8.x

Amit Merchant · December 20, 2021 ·

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!

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?