PHPackages                             huubverbeek/laravel-model-attributes-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. huubverbeek/laravel-model-attributes-validation

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

huubverbeek/laravel-model-attributes-validation
===============================================

Enables attribute-based validation of model attributes automatically during the save process.

v1.0.3(1y ago)21.3k↓50%MITPHP

Since Oct 25Pushed 1y agoCompare

[ Source](https://github.com/HuubVerbeek/laravel-model-attributes-validation)[ Packagist](https://packagist.org/packages/huubverbeek/laravel-model-attributes-validation)[ RSS](/packages/huubverbeek-laravel-model-attributes-validation/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (3)Versions (6)Used By (0)

Model Attributes Validation for Laravel
=======================================

[](#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
------------

[](#installation)

To install this package, use Composer:

```
composer require huubverbeek/laravel-model-attributes-validation
```

Once installed, Laravel will automatically register the service provider.

Support
-------

[](#support)

This project requires PHP version 8 or higher.

Usage
-----

[](#usage)

1. **Define a Validation Rules Class**: Define a class that extends `ValidationRules`, specifying the rules for your model's attributes.

    ```
    use HuubVerbeek\ModelAttributesValidation\ValidationRules;

     /**
      * @property User $model
      */
    class UserValidationRules extends ValidationRules
    {
        public function rules(): array
        {
            /** @note The model being validated is accessible here. */
            $minimumLength = $this->model->getMinimumPasswordLength();

            return [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'email', 'unique:users,email'],
                'password' => ['required',"min:$minimumLength"],
            ];
        }
    }
    ```
2. **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:

    ```
    use HuubVerbeek\ModelAttributesValidation\ValidationRules;

    /**
     * @property User $model
     */
    class UserValidationRules extends ValidationRules implements WithDefaults
    {
         public function rules(): array {
             //
         }

         public function defaults(): array {
             return [
                 'name' => 'Hans Kazan',
             ];
         }
    }
    ```
3. **Apply Validation to Your Model**: Add the `#[ValidationRules(UserValidationRules::class)]` attribute to your model to associate it with the validation rules class.

    ```
    use Illuminate\Database\Eloquent\Model;
    use HuubVerbeek\ModelAttributesValidation\Attributes\ValidationRules;

    #[ValidationRules(UserValidationRules::class)]
    class User extends Model
    {
        // Model properties and methods
    }
    ```
4. **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.

    ```
    $user = User::make([
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => 'securepassword123',
    ]);

    try {
        $user->save(); // Triggers validation
    } catch (ValidationException $e) {
        // Handle validation failure
    }
    ```

Exceptions
----------

[](#exceptions)

- **NotSubclassOfRulesException**: This exception is thrown if the specified rules class does not extend the `ValidationRules` abstract class.

How It Works
------------

[](#how-it-works)

- The `ModelAttributesValidationServiceProvider` listens for the model's `saving` 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
-------

[](#license)

This package is open-source and licensed under the MIT License.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Every ~2 days

Total

4

Last Release

559d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/70261356?v=4)[Huub](/maintainers/HuubVerbeek)[@HuubVerbeek](https://github.com/HuubVerbeek)

---

Top Contributors

[![HuubVerbeek](https://avatars.githubusercontent.com/u/70261356?v=4)](https://github.com/HuubVerbeek "HuubVerbeek (3 commits)")

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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