engency/laravel-model-validation

Model validation for Laravel projects
2,857
Install
composer require engency/laravel-model-validation
Latest Version:v0.3.1
PHP:^7.4|^8.0
Laravel:7 – 11
License:MIT
Last Updated:Jul 23, 2024
Links: GitHub  ·  Packagist
Maintainer: frankkuipers

Laravel model validation

Requirements

  • PHP 7.1+
  • The Laravel framework 7.0+

Installation

You may use composer to install the laravel-model-validation plugin into your Laravel project;

composer require engency/laravel-model-validation

Use the Validatable trait on the models you would like to perform validation on.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Engency\ModelValidation\Validatable;

Class User extends Model
{
   use Validatable;
}

Create a new directory in the app directory called 'ModelValidators'. This directory will contain all rules which apply for the concerning models. For each model using the Validatable trait, create a file called {name of the model}ModelValidator.php. A ModelValidator should look like following;

namespace App\ModelValidators;

use Engency\ModelValidation\ModelValidator;

Class UserModelValidator extends ModelValidator
{
    /**
     * @return array
     */
    public function rules() : array {
        return [
            'name' => 'required|string'
        ];
    }   
}

Validating and creating a new user is now very easy;

$user = User::validateAndCreateNew(['name' => 'John']);

Updating an existing users works almost the same;

$user->validateAndUpdate(['name' => 'John']);

You could add additional sets of rules to each model;

namespace App\ModelValidators;

use Engency\ModelValidation\ModelValidator;

Class UserModelValidator extends ModelValidator
{
    /**
     * @return array
     */
    public function rules() : array {
        return [
            'name' => 'required|string'
        ];
    }

    public function otherRules() : array {
        return [
            'name' => 'required|string|min:5',
            'age' => 'required|integer|min:22'
        ];
    }

}
$user = User::validateAndCreateNew(['name' => 'John', 'age' => 25], 'other');
$user->validateAndUpdate(['name' => 'John', 'age' => 25], 'other');

For a list of all rules, please visit the Laravel Validation documentation; https://laravel.com/docs/validation

Contributors

License

This plugin is licenced under the MIT license.

Related Packages

innoscience/eloquental

A rather clever model for Laravel's Eloquent ORM with self-validation, ordering,...

384 3
usmanhalalit/dryval

Simplify validation in Laravel.

4,679 39
triun/laravel-model-validable

Gives the models the ability to be validated before saved.

473 1
spajz/modval

Simple model validation for Laravel 4.

12 1

Version History

Version Released PHP Laravel License
v0.3.1 ^7.4|^8.0 ^7.0|^8.0|^9.0|^10.0|^11.0 MIT
v0.3.0 >=7.4 ^7.0|^8.0|^9.0|^10.0|^11.0 MIT
v0.2.0 >=7.1 ^7.0|^8.0|^9.0 MIT
v0.1.0 >=7.1 ^7.0|^8.0 MIT