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

Amit Merchant

A blog on PHP, JavaScript, and more

The prohibited validation rule in Laravel 8.x

Sometimes, all you would need is to forcefully prevent some of the fields in the request. Essentially, to “prohibit” or ban the fields to be mandatorily empty or not present in the request at all.

The recent release of Laravel 8.x has just got that. In comes the prohibited validation rule.

The prohibited validation rule

The prohibited rule checks if the field under validation must be empty or not present or throw an error otherwise.

Quoting the PR example here, if you working on an API that involves the license_key field and if you’re expecting this field not to be in the request, you can register the prohibited validation rule like so.

// PUT /api/licenses/123-456
// {"name":"hello-world", "license_key":"random-key"}

$validated = $request->validate([
    'name' => 'required|max:255',
    'license_key' => 'prohibited',
]);

// Response: 422
// The license_key field is prohibited

As you can tell, if the license_key field is present in the request, it will terminate the request with the 422 HTTP response code and throw the error with the message The license_key field is prohibited.

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?