When working with Laravel, one of the key areas you should familiarize yourself with is the directory structure or the relevant folders. Each folder in Laravel has its own specific role and helps you to organize your application better. One of these folders is the "Rules" directory, which contains validation rules that will be applied to incoming requests. This directory helps you ensure that keys of the incoming data are in a specific format and makes it easier for you to manage them.
The "Rules" directory is typically not created in the base folder "app", meaning that whenever you need to create validation rules, you must do so yourself. The goal of this directory is that you can define all validation rules needed in the form of a management class, making their use simpler and their code easier to read.
Assume you have a Laravel application that requires complex validation rules for input data. Instead of having all these validations implemented in controllers, you can utilize the classes of the validation rules inside the "Rules" directory, which allows for better management.
Next, let’s look at a simple example of implementing a validation rule. This example will involve creating a class, implementing a validation rule, and using it in a form submission to demonstrate how you can leverage this directory effectively.
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Uppercase implements Rule
{
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
return strtoupper($value) === $value;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The :attribute must be uppercase.';
}
}
<?php
This line indicates the start of the PHP code.
namespace App\Rules;
This specifies the namespace App\Rules
for the defined class.
use Illuminate\Contracts\Validation\Rule;
This line imports the Rule
contract that needs to be implemented for the validation rule.
class Uppercase implements Rule
You are creating a class named Uppercase
that implements the Rule
, which is responsible for validating input data in uppercase letters.
public function passes($attribute, $value)
This method checks if the provided input is in uppercase and returns true
or false
.
public function message()
This method returns an appropriate message when the validation fails.