PHPackages                             mamadali/laravel-validation-models - 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. mamadali/laravel-validation-models

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

mamadali/laravel-validation-models
==================================

Helps you easily validate your models and eloquent models with specific scenarios and use them in api

v1.0(2y ago)120PHPPHP &gt;=8.0

Since Aug 6Pushed 2y ago1 watchersCompare

[ Source](https://github.com/MamadAliGit/laravel-validation-models)[ Packagist](https://packagist.org/packages/mamadali/laravel-validation-models)[ RSS](/packages/mamadali-laravel-validation-models/feed)WikiDiscussions master Synced yesterday

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

Laravel Validation Models
=========================

[](#laravel-validation-models)

Helps you easily validate your models and eloquent models with specific scenarios and use them in api

[![Latest Stable Version](https://camo.githubusercontent.com/403ada4a7c120be729c025505fcdfb5cdee06512f9e722f372020a240f04c8d9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d616d6164616c692f6c61726176656c2d76616c69646174696f6e2d6d6f64656c732e737667)](https://packagist.org/packages/mamadali/laravel-validation-models)[![Total Downloads](https://camo.githubusercontent.com/b888c4717e74806ff8f1155395672e49bbd7e078c5cd9b3db6bf1bc0ea29f6eb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d616d6164616c692f6c61726176656c2d76616c69646174696f6e2d6d6f64656c732e737667)](https://packagist.org/packages/mamadali/laravel-validation-models)

Installation
============

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
composer require mamadali/laravel-validation-models "*"

```

or add

```
"mamadali/laravel-validation-models": "*"

```

to the "require" section of your `composer.json` file.

---

- [Basic Usage](#basic-usage)
- [Advanced Usage](#advanced-usage)
    - [Multiple Models](#multiple-models)
    - [Inline Validation](#inline-validation)
    - [Scenarios](#scenarios)
    - [Api Response](#api-response)
    - [Get fields in api](#get-fields-in-api)
    - [Events](#events)

---

Basic Usage
===========

[](#basic-usage)

First use trait in your model or eloquent model
-----------------------------------------------

[](#first-use-trait-in-your-model-or-eloquent-model)

in your form use like this

```
class Form
{
    use ModelValidationTrait;
```

in your eloquent models use like this

```
class User extends Model
{
    use EloquentModelValidationTrait;
```

then write your validation rules in validateRules() function in your model

```
    public function validateRules(): array
    {
        return [
            'title' => ['required', "string"],
            'number' => ['required', 'integer'],
        ];
    }
```

and you can load data received from end user to your model and validate data
-&gt;validate() function return true or false

```
Route::post('/test', function (Request $request) {
    // you can pass data from Request or array from user data to newModel function
    $model = Form::newModel($request);
    $validate = $model->validate();

    // if $validate false $model->hasErrors() return false
    $hasErrors = $model->hasErrors();

    // you can get all error message as array with $model->getErrorMessages()
    $errors = $model->getErrorMessages();

    // you can get first error as string with $model->getFirstError()
    $firstErrorMessage = $model->getFirstError();
```

in eloquent models you can just call $model-&gt;save()

```
Route::post('/create-user', function (Request $request) {
    // you can pass data from Request or array from user data to newModel function
    $model = User::newModel($request);

    $model->save();
```

in save function call validate function by default
if you need not call validate function

```
    $model->save(['validate' => false]);
```

Advanced Usage
==============

[](#advanced-usage)

Multiple Models
---------------

[](#multiple-models)

you can new multiple model from your request data if your data list of models

```
    $models = Form::newMultipleModel($request);
    // $models array from your form model with data received in request
```

Inline Validation
-----------------

[](#inline-validation)

you can write your custom validation in your model
write function name as validate{Attribute}() in your model

```
    // your model

    public string $title;

    // validate rules
    .......

     /**
     * @param string $attribute in this example 'title'
     * @param mixed $value value of your attribute
     * @param array $options options passed in validate function
     * @param string $scenario model scenario
     */
    public function validateTitle($attribute, $value, $options, $scenario)
    {
        // your custom validation here
        // and you can add error to the model like this
        $this->addError($attribute, 'error message');
    }
```

Scenarios
---------

[](#scenarios)

you can set multi scenarios for your model like this

```
    public function scenarios() : array
        [
          'scenario1' => ['attribute11', 'attribute12', ...],
          'scenario2' => ['attribute21', 'attribute22', ...],
          ......
        ]
    }
```

and you can pass scenario when create your model

```
    $model = Form::newModel($request, 'scenario1');
    $models = Form::newMultipleModel($request, 'scenario2');
```

also you can set scenario on your model manually

```
    $model = new Form();
    $model->setScenario('scenario1');
    $model->loadModel($request);
```

when load attributes in your model only attributes in scenario set to your model

and you can get scenario currently your model on this

```
    $model->getScenario();
```

---

you can handle your validation rules with scenarios like this

```
    public function validateRules(): array
    {
        return [
            'title' => Rule::when($this->getScenario() == 'scenario1', ['required', 'string']),
            'number' => Rule::when($this->getScenario() == 'scenario2', ['required', 'integer']),
        ];
    }
```

---

Api Response
------------

[](#api-response)

you can return your model data as response in your api
in your api controller

```
    return $model->responseAsJson();
```

in this order if your model has errors your response status code set to 422 and your error message in body
else return your model attributes with value in body

in some api if you need No Content with 204 status code response you can use this function

```
    return $model->responseNoContent();
```

---

you can customize your fields in api response with overwrite fields() function in your model like this

```
    public function fields(): array
    {
        // list of fields in response
        return [
            // field id cast to integer
            'id:int',
            // field title cast to string
            'title:string',
            // you can use your database relation like this (return relation model. you can custom fields in relation model)
            'dbRelation',
            // you can use specific field from your db relation
            'dbRelation.price',
            // and you can write custom field like this
            'custom:float' => function (self $model) {
                return $this->custom();
            },
        ];
    }
```

now supported cast type: int, string, float, bool

---

Get fields in api
-----------------

[](#get-fields-in-api)

you can write extra fields in your model like this

```
    public function extraFields(): array
    {
        // list of fields in response
        return [
            'extraTitle',
            ....
        ];
    }
```

extra fields are not included in the api response by default
and to get extra fields in the api response you need to add 'expand' parameter to your query params in request

in fields and extraFields method you can return recursively you model fields

`http://127.0.0.1/api/test?expand=extraField1,extraField2`
in this request get all fields in fields() function and fields defined in 'expand' parameter

and you can get specific fields in your response by add 'fields' parameter in query params

`http://127.0.0.1/api/test?fields=id,title&expand=extraField1`
in this request only get id,title and extraField1

---

Events
------

[](#events)

beforeValidate method is invoked before validation starts.
You may override this method in your model
If `false` is returned, the validation will stop and the model is considered invalid.

```
    public function beforeValidate() : bool
    {
        ... your code here ...
        return true;
    }
```

afterValidate method is invoked after validation ends.
You may override this method in your model

```
    public function afterValidate(): void
    {
        .... your code here ....
    }
```

beforeSave method is called at the beginning of inserting or updating a record in eloquent models. Override this method in your eloquent model
If `false`, the insertion or updating will be cancelled.

```
    public function beforeSave(array $options = []): bool
    {
        ... your code here ...
        return true;
    }
```

This method is called at the end of inserting or updating a record in eloquent models.
Override this method in your eloquent model:

```
    public function afterSave(array $options = []): void
    {
        ... your code here ...
    }
```

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity52

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

Total

2

Last Release

901d ago

Major Versions

v0.1 → v1.02024-01-15

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b1a551511f14b87b786d64eb6869179ebb700c6faaf9c6bc7795346dfffee41?d=identicon)[MamadAli](/maintainers/MamadAli)

---

Top Contributors

[![MamadAliGit](https://avatars.githubusercontent.com/u/70506682?v=4)](https://github.com/MamadAliGit "MamadAliGit (8 commits)")

### Embed Badge

![Health badge](/badges/mamadali-laravel-validation-models/health.svg)

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

###  Alternatives

[illuminate/auth

The Illuminate Auth package.

10528.2M1.2k](/packages/illuminate-auth)[illuminate/routing

The Illuminate Routing package.

1419.2M3.0k](/packages/illuminate-routing)[illuminate/validation

The Illuminate Validation package.

18838.2M1.7k](/packages/illuminate-validation)[spatie/laravel-honeypot

Preventing spam submitted through forms

1.6k6.8M75](/packages/spatie-laravel-honeypot)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

762649.9k18](/packages/wendelladriel-laravel-validated-dto)

PHPackages © 2026

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