Download the PHP package huubverbeek/laravel-model-attributes-validation without Composer
On this page you can find all versions of the php package huubverbeek/laravel-model-attributes-validation. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download huubverbeek/laravel-model-attributes-validation
More information about huubverbeek/laravel-model-attributes-validation
Files in huubverbeek/laravel-model-attributes-validation
Package laravel-model-attributes-validation
Short Description Enables attribute-based validation of model attributes automatically during the save process.
License MIT
Informations about the package laravel-model-attributes-validation
Model Attributes Validation for Laravel
This package enables model attribute validation in Laravel by defining validation rules through attributes on your Eloquent models. It leverages PHP's attributes feature to declare validation rules directly on the model class, facilitating attribute-driven validation.
Installation
To install this package, use Composer:
Once installed, Laravel will automatically register the service provider.
Support
This project requires PHP version 8 or higher.
Usage
-
Define a Validation Rules Class: Define a class that extends
ValidationRules
, specifying the rules for your model's attributes. -
Defining Defaults for the Validatable Attributes: In some cases you might want to define default values for validatable attributes if you are creating a resource. You can do this by implementing the
WithDefaults
interface: -
Apply Validation to Your Model: Add the
#[ValidationRules(UserValidationRules::class)]
attribute to your model to associate it with the validation rules class. - Saving and Validation:
When you attempt to save the model, the package will automatically validate the model's attributes according to the specified rules. If validation fails, a
ValidationException
will be thrown.
Exceptions
- NotSubclassOfRulesException: This exception is thrown if the specified rules class does not extend the
ValidationRules
abstract class.
How It Works
- The
ModelAttributesValidationServiceProvider
listens for the model'ssaving
event. - Before saving a model, the service attempts to retrieve and validate the model attributes based on the validation rules class defined in the
#[ValidationRules(...)]
attribute. - Validation rules are dynamically applied, and if they are not met, a
ValidationException
is thrown, halting the save operation.
License
This package is open-source and licensed under the MIT License.