Managing field logic in a separate file through rules can greatly enhance the organization and reusability of your codebase. By employing this approach, you can utilize your logic for various validations throughout your project. Let's demonstrate this with an example:
Suppose we have a Permission enum in our Laravel project, and when an admin assigns a permission to a user, we need to verify if the permission is valid. To accomplish this, we'll create the Permission enum using BenSampo/laravel-enum package:
php artisan make:enum Permission
Next, we'll define some sample permissions in the Permission enum:
const ManagePermissions = 'manage-permissions';
const ManageUsers = 'manage-users';
const ManagePosts = 'manage-posts';
Now, let's proceed to create the ValidPermissionRule to handle permission validation:
php artisan make:rule ValidPermissionRule
The validate method in the ValidPermissionRule class will accept three parameters:
-
$attribute
: name of the field -
$value
: value of the attribute -
$fail
: a callback to use if the validation is not valid
Our logic for this rule is quite straightforward: we need to check if the $value
exists in the Permission
enum; if it does, the validation passes; otherwise, it fails, and we'll use the $fail
callback to display an error message:
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! in_array($value, Permission::getValues())) {
$fail($attribute.' is invalid.');
}
}
By using this ValidPermissionRule, you can now easily apply permission validation in various parts of your application, ensuring that only valid permissions are assigned to users.
Now that we have created the ValidPermissionRule, we can use it in our Laravel project to validate permissions. Let's explore two methods of using this rule.
You can use the rule directly in your controller or wherever you need to validate the permission:
$request->validate([
'permission' => new ValidPermissionRule,
]);
Alternatively, you can extend the rule and give it a name for easier usage across your application:
First, extend the rule in a service provider or directly in the boot method of the AppServiceProvider:
use Illuminate\Support\Facades\Validator;
Validator::extend(
'valid_permission',
'\\App\\Rules\\ValidPermissionRule@validate'
);
Now you can use the extended rule with the name valid_permission in your validations:
$request->validate([
'permission' => 'valid_permission',
]);
By using this structured approach and custom validation rule, you can easily maintain and reuse your permission validation logic throughout your Laravel application.
Top comments (0)