PHPackages                             steven-fox/laravel-model-validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. steven-fox/laravel-model-validation

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

steven-fox/laravel-model-validation
===================================

Salvation for your model validation.

v0.1.0(1y ago)3241[4 PRs](https://github.com/steven-fox/laravel-model-validation/pulls)MITPHPPHP ^8.2CI passing

Since May 28Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/steven-fox/laravel-model-validation)[ Packagist](https://packagist.org/packages/steven-fox/laravel-model-validation)[ Docs](https://github.com/steven-fox/laravel-model-validation)[ GitHub Sponsors]()[ RSS](/packages/steven-fox-laravel-model-validation/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (17)Versions (6)Used By (0)

Salvation for your model validation.
====================================

[](#salvation-for-your-model-validation)

[![Latest Version on Packagist](https://camo.githubusercontent.com/597b89eff7d7a856e57d1fe8df273c99723df4c9c7a3e624637f720105ecb100/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73746576656e2d666f782f6c61726176656c2d6d6f64656c2d76616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/steven-fox/laravel-model-validation)[![GitHub Tests Action Status](https://camo.githubusercontent.com/29655f4c421676c6fdfc345b29484896a8272aacc9d5a315c7aeca59c3bdc75a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73746576656e2d666f782f6c61726176656c2d6d6f64656c2d76616c69646174696f6e2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/steven-fox/laravel-model-validation/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/e5e4c18772e762085f3d59dc03cbe3cf23c8b6f9fd31e1a925627c315cbb47c0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73746576656e2d666f782f6c61726176656c2d6d6f64656c2d76616c69646174696f6e2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/steven-fox/laravel-model-validation/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/508d5e932bd22b2517c025dac55e613ad1cdc1991346175061610bf56e33aeea/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73746576656e2d666f782f6c61726176656c2d6d6f64656c2d76616c69646174696f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/steven-fox/laravel-model-validation)

This package makes it easy to add validation helpers to your Eloquent models. Some similar packages already exist, but this package aims to achieve flawless functionality in a customizable, Laravel-esque way.

The purpose of this package is to:

1. Reduce code duplication by providing a single location where the baseline validation configuration is defined for your models.
2. Make it easy to retrieve that configuration to supplement specific validation scenarios (like FormRequests, admin forms/actions, console input, etc.).
3. Provide data integrity for applications by ensuring models adhere to a particular set of rules that is independent of UI.

Key Features
------------

[](#key-features)

- Adds several validation methods to your models like `validate()`, `passesValidation()`, and `failsValidation()`.
- Validation can be configured to occur automatically when saving the model (opt-in via an interface and can be turned off globally when needed).
- Validation rules can be configured as a single definition or broken out into independent rules for creating vs. updating.
- Validation rules can be superseded or mixed with custom rules at runtime.
- The data used for validation can be customized and transformed prior to validating.
- Models can define custom validation messages and attribute names.
- The validation configuration (data, rules, messages, names) are accessible via public methods, so incorporating them into validation processes with requests, controllers, Nova, Filament, etc. is easy.
- Model event hooks for `validating` and `validated` are provided, easy to work with, and can be used in your existing model observers.
- Custom validation listeners can be defined for specific model events.
- Helpers are provided to work with `Unique` rules that need to ignore the current model record when updating.
- A custom ValidationException is thrown that includes the model that was validated as a property to assist with debugging, logging, and error messages.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require steven-fox/laravel-model-validation
```

Usage
-----

[](#usage)

### The `ValidatesAttributes` Trait

[](#the-validatesattributes-trait)

Add validation functionality to a Model by:

1. Adding the `StevenFox\LaravelModelValidation\ValidatesAttributes` trait to the model.
2. Defining the rules on the model via one or more of the available methods: `baseValidationRules()`, `validationRulesUniqueToCreating()`, `validationRulesUniqueToUpdating()`, `validationRulesForCreating()`, `validationRulesForUpdating()`.

```
use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model
{
    use ValidatesAttributes;

    protected function baseValidationRules(): array
    {
        return [
            // rules go here as ['attribute' => ['rule1', 'rule2', ...]
            // like a normal validation setup
        ];
    }

    // Other methods are available for more control over rules... see below.
}

$model = new ValidatingModel($request->json());

$model->validate(); // A ModelValidationException is thrown if validation fails.
$model->save();

// Other helpful methods...
$passes = $model->passesValidation(); // An exception, will *not* be thrown if validation fails.
$fails = $model->failsValidation(); // No exception thrown here, either.
$validator = $model->validator();
```

### The `ValidatesWhenSaving` Interface

[](#the-validateswhensaving-interface)

You can make a model automatically perform validation when saving by adding the `\StevenFox\LaravelModelValiation\Contracts\ValidatesWhenSaving` interface. This is an **opt-in** feature. Without implementing this interface on your individual models, you can still perform validation on command; it simply won't be performed during the `save()` process automatically.

```
use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\Contracts\ValidatesWhenSaving;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model implements ValidatesWhenSaving
{
    use ValidatesAttributes;

    // This model will now validate upon saving.
}
```

#### Validation Listeners

[](#validation-listeners)

By default, this package will register an event listener for the `creating` and `updating` model events that performs the validation prior to saving the model. You can customize this behavior by overloading the static `validatingListeners()` method on your models. Here is the default implementation that you can adjust to your needs.

```
protected static function validatingListeners(): array
{
    return [
        'creating' => ValidateModel::class,
        'updating' => ValidateModel::class,
    ];
}
```

> Note: We specifically use the `creating` and `updating` events over the more general `saving` event so that we don't redundantly validate a model that is "saved" without any changed attributes (which does NOT fire an `updating` event, saving us from redundancy).

> Note: Keep in mind that the automatic validation process is implemented with Laravel's model event system. Thus, if you perform a `saveQuietly()` or do something else that disables/halts the model's event chain, you will disable the automatic validation as a consequence.

### More Control Over Validation Rules

[](#more-control-over-validation-rules)

You can use the following methods to gain finer control over the validation rules used in particular situations.

```
use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model
{
    use ValidatesAttributes;

    /**
     * Define rules that are common to both creating and updating a model record.
     */
    protected function baseValidationRules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            // more rules...
        ];
    }

    /**
     * Define the rules that are unique to creating a record.
     * These rules will be *combined* with the common validation rules.
     *
     */
    protected function validationRulesUniqueToCreating(): array
    {
        return ['a_unique_column' => Rule::unique('table')];
    }

    /**
     * Define the rules that are unique to updating a record.
     * These rules will be combined with the common validation rules.
     *
     */
    protected function validationRulesUniqueToUpdating(): array
    {
        return ['a_unique_column' => Rule::unique('table')->ignoreModel($this)];
    }

    /**
     * Define the rules that are used when creating a record.
     * If you overload this method on your model, the 'baseValidationRules'
     * will not be used by default.
     */
    protected function validationRulesForCreating(): array
    {
        // ...
    }

    /**
     * Define the rules that are used when updating a record.
     * If you overload this method on your model, the 'baseValidationRules'
     * will not be used by default.
     */
    protected function validationRulesForUpdating(): array
    {
        // ...
    }
}
```

#### Unique Columns

[](#unique-columns)

Specifying an attribute as `unique` is a common validation need. Therefore, this package provides a shortcut that you can use in the `baseValidationRules()` method for your unique columns. The helper function will simply define a `Unique` rule for the attribute, and when the model record already exists in the database, the rule will automatically invoke the `ignoreModel($this)` method.

```
/**
 * Define rules that are common to both creating and updating a model record.
 */
protected function baseValidationRules(): array
{
    return [
        'email' => [
            'required',
            'email',
            'max:255',
            $this->uniqueRule(), // adds a unique rule that handles ignoring the current record on update
        ],
        // more rules...
    ];
}
```

### Runtime Customization for Rules

[](#runtime-customization-for-rules)

#### Superseding Rules

[](#superseding-rules)

You can use the `setSupersedingValidationRules()` method to set temporary rules that will **replace** all other rules defined on the model.

```
$model = new ValidatingModel();

$customRules = [
    // ...
];

$model->setSupersedingValidationRules($customRules);

$model->validate(); // The validator will **only** use the $customRules for validation.

$model->clearSupersedingValidationRules();
$model->validate(); // The validator will now go back to using the normal rules defined on the model.
```

> Note: You can temporarily disable a specific model instance's validation by setting the `supersedingValidationRules` to an empty array. The validation process will still run, but with no rules to validate against, the model will automatically pass.

```
$model = new ValidatingModel();

$model->setSupersedingValidationRules([]);

$model->validate(); // Validation will run, but with no rules defined, no actual validation will occur.

$model->clearSupersedingValidationRules();
$model->validate(); // Validation will occur normally.
```

#### Mixin Rules

[](#mixin-rules)

You can use the `addMixinValidationRules()` and `setMixinValidationRules()` methods to define rules that will be **merged** with the other rules defined on the model. The rules you mixin for a particular attribute will replace any existing rules for that attribute.

For example, suppose your model specifies that a dateTime column must simply be a `date` by default, but for a particular situation, you want to ensure that the attribute's value is a date *after a particular moment*. You can do this by mixing in this custom ruleset for this attribute at runtime.

```
$model = new ValidatingModel();

// Normally, the ValidatingModel specifies that the 'date_attribute'
// is simply a 'date'.

// However, here we will specify that it must be a date after tomorrow.
$mixinRules = [
    'date_attribute' => ['date', 'after:tomorrow']
];

$model->addMixinValidationRules($mixinRules);

$model->validate(); // The validator will use a *combination* of the mixin rules and the standard rules defined within the model.

$model->clearMixinValidationRules();
$model->validate(); // The validator will now go back to using the normal rules defined on the model.
```

### Validation Data

[](#validation-data)

By default, this package will use the model's `getAttributes()` method as the data to pass to the validator instance. Normally, the array returned from the `getAttributes()` method represents the raw values that will be stored within the database. This means attributes with casting will be mutated into the format used for storage, making the validation logic as seamless as possible. For example, most date attributes on models are cast to `Carbon` instances, but when validating dates, the validator needs to receive the string representation of the date, not a `Carbon` instance.

If you need to customize the attributes used as data for validation, you can do so in two ways:

1. Overload the `rawAttributesForValidation()` method and return what you need.
2. Overload the `prepareAttributesForValidation($attributes)` method to transform the default attribute values into a validation-ready state.

### Accessing Validation Configuration

[](#accessing-validation-configuration)

You can access a model's validation rules, data, messages, and attribute names using the following methods.

```
$model = new ValidatingModel();

// --- Rules ---
// Retrieve all rules with
$allRules = $model->validationRules();
// or, retrieve rules for certain attributes...
$specificRules = $model->validationRules('attr_1', 'attr_2', ...);

// --- Data ---
// Retrieve all validation data with
$allData = $model->validationData();
// or, retrieve the data for certain attributes...
$specificData = $model->validationData('attr_1', 'attr_2', ...);

// --- Custom Messages and Attribute Names ---
$customMessages = $model->customValidationMessages();
$customAttributeNames = $model->customValidationAttributeNames();
```

### Globally Disabling Validation When Saving

[](#globally-disabling-validation-when-saving)

It is possible to disable the automatic validation during the save process for models that implement the `ValidatesOnSave` interface. This can be helpful when setting up a particular test, for example.

#### Option 1

[](#option-1)

Call the static `disableValidationWhenSaving()` on a validating model class. This will disable validation until you explicitly activate it again. This is similar to the `Model::unguard()` concept, and like unguarding, you would likely do the disabling of validation in the `boot` method of a `ServiceProvider`.

```
// Perhaps in a ServiceProvider...

public function boot(): void
{
    ValidatingModel::disableValidationWhenSaving();

    // All models that validate their attributes and implement
    // the ValidatesWhenSaving interface will no longer perform
    // that automatic validation during the saving process.
}
```

#### Option 2

[](#option-2)

Call the static `whileValidationDisables()` method, passing in a callback that executes the logic you would like to perform while automatic validation is globally disabled. This is similar to the `Model::unguarded($callback)` concept.

```
ValidatingModel::whileValidationDisabled(function () {
    // do something while automatic validation is globally disabled...
});
```

### Validation Model Events

[](#validation-model-events)

This package adds `validating` and `validated` model events. It also registers these as "observable events", which means you can listen for them within your model observer classes, like you would for `saving`, `deleting`, etc.

When implementing a listener for this event, the model record emitting the event and the related validator instance will be supplied to the callback.

```
\Illuminate\Support\Facades\Event::listen(
    'eloquent.validating*',
    function (Model $model, Validator $validator) {
        // Do something when any model is "validating".
        // $model will be an instance of Model and ValidatesAttributes.
    }
);
```

Similar to the other observable model events, this package provides static `validating($callback)` and `validated($callback)` methods that you can use to register listeners for these events.

```
ValidatingModel::validating(function (ValidatingModel $model, Validator $validator) {
    // ...
})

ValidatingModel::validated(function (ValidatingModel $model, Validator $validator) {
    // ...
})
```

### The Validator Instance

[](#the-validator-instance)

You can access the Validator instance that was last used to perform the `validate()` process with the `validator()` method.

```
$model = new ValidatingModel($request->json());

$validator = $model->validate();

// Or...

$model->validate();
$validator = $model->validator();
```

> Note: A new validator instance is instantiated and stored on the model instance each time the `validate()` method is invoked.

```
$model = new ValidatingModel(...);

$validator1 = $model->validate();

$validator2 = $model->validate();

// $validator1 is *not* a reference to the same object as $validator2.
```

#### Customizing the Validator

[](#customizing-the-validator)

You can customize the validator instance with the `beforeMakingValidator()` and `afterMakingValidator($validator)` methods on a model.

> Note: The `afterMakingValidator()` method can be a great place to specify `after` hooks for your validation process.

You can pass custom validation messages and custom attribute names to the validator via the `customValidationMessages()` and `customValidationAttributeNames()` methods respectively.

```
class ValidatingModel extends Model
{
    use ValidatesAttributes;

    public function customValidationMessages(): array
    {
        return ['email.required' => 'We need to know your email address.']
    }

    public function customValidationAttributeNames(): array
    {
        return ['ip_v4' => 'ip address'];
    }
}
```

### Validation Exception

[](#validation-exception)

When the `validate()` method is invoked and validation fails, a `ModelValidationException` is thrown by default. This exception extends Laravel's `ValidationException`, but stores a reference to the model record that failed validation to make debugging or error messages easier to handle.

You can provide your own validation exception by overloading the `validationExceptionClass()` or `throwValidationException($validator)` methods.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Steven Fox](https://github.com/steven-fox)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance65

Regular maintenance activity

Popularity11

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 75.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

711d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c3c9b257c10b41dc9dcad9d29657e430ea0b902c91a0e9392fa9f57bf48bd349?d=identicon)[stevenfox](/maintainers/stevenfox)

---

Top Contributors

[![steven-fox](https://avatars.githubusercontent.com/u/62109327?v=4)](https://github.com/steven-fox "steven-fox (37 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (6 commits)")

---

Tags

laravelsteven-foxlaravel-model-validation

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/steven-fox-laravel-model-validation/health.svg)

```
[![Health](https://phpackages.com/badges/steven-fox-laravel-model-validation/health.svg)](https://phpackages.com/packages/steven-fox-laravel-model-validation)
```

###  Alternatives

[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M106](/packages/propaganistas-laravel-phone)[watson/validating

Eloquent model validating trait.

9723.3M47](/packages/watson-validating)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.0M60](/packages/spatie-laravel-honeypot)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
