Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), 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-digest 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.

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.

Comments?