PHPackages                             fourfortymedia/eloquent-model-guard - 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. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. fourfortymedia/eloquent-model-guard

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

fourfortymedia/eloquent-model-guard
===================================

1.6(2y ago)135PHPPHP &gt;=8.0

Since Aug 15Pushed 2y agoCompare

[ Source](https://github.com/fourfortymedia/eloquent-model-guard)[ Packagist](https://packagist.org/packages/fourfortymedia/eloquent-model-guard)[ RSS](/packages/fourfortymedia-eloquent-model-guard/feed)WikiDiscussions main Synced today

READMEChangelog (2)Dependencies (5)Versions (8)Used By (0)

Eloquent Model Guard - Readme
=============================

[](#eloquent-model-guard---readme)

Welcome to the readme for the **eloquent-model-guard** Laravel package. This package brings an array of enhancements to data validation for Eloquent models, providing developers with improved control over data integrity and validation rules. Let's dive into the details of this package.

Attributes
----------

[](#attributes)

The **eloquent-model-guard** package introduces the ability to add structured and machine-readable metadata information to declarations. This enhances the control over data validation, particularly within Eloquent models, and allows for finer customization of validation rules based on specific scenarios.

Background
----------

[](#background)

Database fields are characterized by types that define the nature of data they can store. These types ensure data integrity and consistency by enforcing validation rules. Typically, these setups are performed within migrations. Different data types represent various kinds of data such as numbers, strings, and dates. By indicating the type of a field, the database can validate and enforce rules to ensure only valid data is stored. This not only prevents errors but also enhances query performance and data accuracy.

While migrations establish data integrity upon storage, they are executed only once. The **eloquent-model-guard** package empowers users to update and adapt validation rules within the model. This offers a significant advantage in responding to changing application requirements. Developers can now effortlessly customize validation rules based on evolving business needs without altering the database structure. This dynamic and agile approach enhances the efficiency and adaptability of validation, resulting in a more robust and responsive application.

Added Features
--------------

[](#added-features)

The **eloquent-model-guard** package comes with several notable additions:

- **Custom Validation Rules:** Developers can define validation rules using custom attributes: `OnCreateRules` and `OnUpdateRules`. This customization allows fine-tuning of validation rules based on specific scenarios.
- **`validateUsing` Method:** The `Model` class now includes a `validateUsing` method, supporting the use of custom validation rules.
- **`protected array $rules;` Property:** A new property has been added to conveniently store validation rules.

Changes
-------

[](#changes)

The following changes have been made to improve validation in Eloquent models:

- The `booted` method within the `Model` class now automatically triggers validation during creation and updating.
- A new static call method `validateUsing` has been introduced within the `__callStatic` method. This method can be used dynamically and statically.

Context
-------

[](#context)

The enhancements brought by the **eloquent-model-guard** package greatly enhance data validation for Eloquent models. The introduction of `OnCreateRules` and `OnUpdateRules` attributes allows developers to craft specific validation rules for model creation and updates, respectively. This granularity in validation empowers developers to fine-tune validation for individual models, properties, or attributes, promoting cleaner code organization and more efficient validation logic.

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

[](#installation)

```
 composer require fourfortymedia/eloquent-model-guard
```

In your eloquent model, add the following

```
class User extends Model {
     use \FourFortyMedia\EloquentModelGuard\Concerns\HasEloquentModelGuard;
}
```

Examples
--------

[](#examples)

Let's explore some usage examples to demonstrate how to take advantage of the new attributes:

1. **Validation on Creation:**

    ```
    use Illuminate\Database\Eloquent\Validations\OnCreateRules;

    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        #[OnCreateRules(['roles.*' => 'rule1|rule2')]
        private array $roles = [];
    }
    ```
2. **Validation on Update:**

    ```
    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;

    #[OnUpdateRules(['email' => 'required|email'])]
    class User extends Model {
        // ...
    }
    ```
3. **Combining Both Attributes:**

    ```
    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;

    #[OnUpdateRules(['email' => 'required|email'])]
    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        // ...
    }
    ```
4. **Using on Model Fields:**Note: When using this on the model attributes, use either `private` or `protected` on those attributes so that they don't interfere with your `attributes`

    ```
    use Illuminate\Database\Eloquent\Validations\OnUpdateRules;

    #[OnUpdateRules(['email' => 'required|email'])]
    #[OnCreateRules(['name' => 'required', 'email' => 'required|email'])]
    class User extends Model {
        #[OnUpdateRules(['required'])]
        protected string $name;

        #[OnUpdateRules(['email' => 'required|email'])]
        #[OnCreateRules('required|email')]
        protected string $email;
    }
    ```

    ```
    please note that when using it on a sigle property, you may pass and accosiative array with a key that is

    ```

    the same as the property with the value as the rules or pass rules as array or keys
5. **Custom Rules with Validation:**

    ```
    $product = Product::validateUsing(function ($rules) {
        $rules['price'] = 'numeric|min:0';
        return $rules;
    })->create($data);
    ```
6. **Automatic Validation on Creation and Updating:**

    ```
    protected static function booted()
    {
        static::creating(function (self $model) {
            $model->getModelRules(useOnCreateRules: false);
            $model->getPropertyRules(useOnCreateRules: false);
            $model->validate();
        });
        static::updating(function (self $model) {
            $model->getModelRules();
            $model->getPropertyRules();
            $model->validate();
        });
    }
    ```

Note
----

[](#note)

Please note that this pull request is a work in progress and is being submitted for initial review and feedback. Further improvements and adjustments will be made based on the feedback received.

Remember that the package's features only take effect when the attributes are applied to the model or properties. This package does not enforce any developer to use it, offering flexibility while providing powerful validation capabilities.

For any inquiries or feedback, feel free to contact Mr. Rikhotso, the creator of this package. Your thoughts and suggestions are highly valued.

###  Health Score

25

—

LowBetter than 35% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

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 ~0 days

Total

7

Last Release

1054d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/21697378?v=4)[Ntiyiso Rikhotso](/maintainers/ntiyiso-rikhotso)[@ntiyiso-rikhotso](https://github.com/ntiyiso-rikhotso)

---

Top Contributors

[![ntiyiso-rikhotso](https://avatars.githubusercontent.com/u/21697378?v=4)](https://github.com/ntiyiso-rikhotso "ntiyiso-rikhotso (21 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fourfortymedia-eloquent-model-guard/health.svg)

```
[![Health](https://phpackages.com/badges/fourfortymedia-eloquent-model-guard/health.svg)](https://phpackages.com/packages/fourfortymedia-eloquent-model-guard)
```

###  Alternatives

[statamic-rad-pack/runway

Eloquently manage your database models in Statamic.

135224.7k7](/packages/statamic-rad-pack-runway)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

59437.0k9](/packages/jeremy379-laravel-openid-connect)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[duncanmcclean/statamic-cargo

Comprehensive e-commerce addon for Statamic. Build bespoke e-commerce sites without the complexity.

3416.9k](/packages/duncanmcclean-statamic-cargo)

PHPackages © 2026

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