Model validation for Laravel projects
engency/laravel-model-validation is a Laravel package for model validation for laravel projects.
It currently has 0 GitHub stars and 2.754 downloads on Packagist (latest version v0.3.1).
Install it with composer require engency/laravel-model-validation.
Discover more Laravel packages by engency
or browse all Laravel packages to compare alternatives.
Last updated
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
This plugin is licenced under the MIT license.