PHP code example of steven-fox / laravel-model-validation

1. Go to this page and download the library: Download steven-fox/laravel-model-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

steven-fox / laravel-model-validation example snippets


use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model
{
    use ValidatesAttributes;
    
    protected function baseValidationRules(): array
    {
        return [
            // rules go here as ['attribute' => ['rule1', 'rule2', ...]
            // like a normal validation setup
        ];
    }
    
    // Other methods are available for more control over rules... see below.
}

$model = new ValidatingModel($request->json());

$model->validate(); // A ModelValidationException is thrown if validation fails.
$model->save();

// Other helpful methods...
$passes = $model->passesValidation(); // An exception, will *not* be thrown if validation fails.
$fails = $model->failsValidation(); // No exception thrown here, either.
$validator = $model->validator();

use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\Contracts\ValidatesWhenSaving;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model implements ValidatesWhenSaving
{
    use ValidatesAttributes;
    
    // This model will now validate upon saving.
}

protected static function validatingListeners(): array
{
    return [
        'creating' => ValidateModel::class,
        'updating' => ValidateModel::class,
    ];
}

use Illuminate\Database\Eloquent\Model;
use StevenFox\LaravelModelValidation\ValidatesAttributes;

class ValidatingModel extends Model
{
    use ValidatesAttributes;
    
    /**
     * Define rules that are common to both creating and updating a model record.
     */
    protected function baseValidationRules(): array
    {
        return [
            'name' => ['efine the rules that are unique to updating a record.
     * These rules will be combined with the common validation rules.
     * 
     */
    protected function validationRulesUniqueToUpdating(): array
    {
        return ['a_unique_column' => Rule::unique('table')->ignoreModel($this)];
    }
    
    /**
     * Define the rules that are used when creating a record.
     * If you overload this method on your model, the 'baseValidationRules'
     * will not be used by default. 
     */
    protected function validationRulesForCreating(): array
    {
        // ...
    }
    
    /**
     * Define the rules that are used when updating a record.
     * If you overload this method on your model, the 'baseValidationRules'
     * will not be used by default. 
     */
    protected function validationRulesForUpdating(): array
    {
        // ...
    }
}

/**
 * Define rules that are common to both creating and updating a model record.
 */
protected function baseValidationRules(): array
{
    return [
        'email' => [
            's...
    ];
}

$model = new ValidatingModel();

$customRules = [
    // ...
];

$model->setSupersedingValidationRules($customRules);

$model->validate(); // The validator will **only** use the $customRules for validation.

$model->clearSupersedingValidationRules();
$model->validate(); // The validator will now go back to using the normal rules defined on the model.

$model = new ValidatingModel();

$model->setSupersedingValidationRules([]);

$model->validate(); // Validation will run, but with no rules defined, no actual validation will occur.

$model->clearSupersedingValidationRules();
$model->validate(); // Validation will occur normally.

$model = new ValidatingModel();

// Normally, the ValidatingModel specifies that the 'date_attribute'
// is simply a 'date'.

// However, here we will specify that it must be a date after tomorrow.
$mixinRules = [
    'date_attribute' => ['date', 'after:tomorrow']
];

$model->addMixinValidationRules($mixinRules);

$model->validate(); // The validator will use a *combination* of the mixin rules and the standard rules defined within the model.

$model->clearMixinValidationRules();
$model->validate(); // The validator will now go back to using the normal rules defined on the model.

$model = new ValidatingModel();

// --- Rules ---
// Retrieve all rules with
$allRules = $model->validationRules();
// or, retrieve rules for certain attributes...
$specificRules = $model->validationRules('attr_1', 'attr_2', ...);

// --- Data ---
// Retrieve all validation data with
$allData = $model->validationData();
// or, retrieve the data for certain attributes...
$specificData = $model->validationData('attr_1', 'attr_2', ...);

// --- Custom Messages and Attribute Names ---
$customMessages = $model->customValidationMessages();
$customAttributeNames = $model->customValidationAttributeNames();

// Perhaps in a ServiceProvider...

public function boot(): void
{
    ValidatingModel::disableValidationWhenSaving();
    
    // All models that validate their attributes and implement 
    // the ValidatesWhenSaving interface will no longer perform
    // that automatic validation during the saving process.
}

ValidatingModel::whileValidationDisabled(function () {
    // do something while automatic validation is globally disabled...
});

\Illuminate\Support\Facades\Event::listen(
    'eloquent.validating*',
    function (Model $model, Validator $validator) {
        // Do something when any model is "validating".
        // $model will be an instance of Model and ValidatesAttributes.
    }
);

ValidatingModel::validating(function (ValidatingModel $model, Validator $validator) {
    // ...
})

ValidatingModel::validated(function (ValidatingModel $model, Validator $validator) {
    // ...
})

$model = new ValidatingModel($request->json());

$validator = $model->validate();

// Or...

$model->validate();
$validator = $model->validator();

$model = new ValidatingModel(...);

$validator1 = $model->validate();

$validator2 = $model->validate();

// $validator1 is *not* a reference to the same object as $validator2.

class ValidatingModel extends Model
{
    use ValidatesAttributes;
    
    public function customValidationMessages(): array
    {
        return ['email.