Skip to content

This package is an alternative to the Laravel built-in validation rules exists and unique. It uses Eloquent models instead of directly querying the database.

License

Notifications You must be signed in to change notification settings

korridor/laravel-model-validation-rules

Repository files navigation

Laravel model validation rules

This package is an alternative to the Laravel built-in validation rules exist and unique. This has the following advantages:

  • It uses existing models instead of directly querying the database.
  • The rule can be easily extended with the Eloquent builder.
  • Softdeletes are working

Installation

You can install the package via composer with following command:

composer require korridor/laravel-model-validation-rules

Translation

If you want to customize the translations of the validation errors you can publish the translations of the package to the resources/lang/vendor/modelValidationRules folder.

php artisan vendor:publish --provider="Korridor\LaravelModelValidationRules\ModelValidationServiceProvider"

Rules

ExistEloquent

UniqueEloquent

Usage examples

PostStoreRequest

public function rules()
{
    $postId = $this->post->id;
    
    return [
        'username' => [new UniqueEloquent(User::class, 'username')],
        'title' => ['string'],
        'content' => ['string'],
        'comments.*.id' => [
            'nullable',
            new ExistEloquent(Comment::class, null, function (Builder $builder) use ($postId) {
                return $builder->where('post_id', $postId);
            }),
        ],
        'comments.*.content' => ['string']
    ];
}

PostUpdateRequest

public function rules()
{
    $postId = $this->post->id;
    
    return [
        'id' => [new ExistEloquent(Post::class)],
        'username' => [new UniqueEloquent(User::class, 'username')->ignore($postId)],
        'title' => ['string'],
        'content' => ['string'],
        'comments.*.id' => [
            'nullable',
            new ExistEloquent(Comment::class, null, function (Builder $builder) use ($postId) {
                return $builder->where('post_id', $postId);
            }),
        ],
        'comments.*.content' => ['string']
    ];
}

Contributing

I am open for suggestions and contributions. Just create an issue or a pull request.

Testing

composer test
composer test-coverage

Codeformatting/Linting

composer fix
composer lint

Credits

The structure of the repository and the TestClass is inspired by the project laravel-validation-rules by spatie.

License

The MIT License (MIT). Please see license file for more information.

About

This package is an alternative to the Laravel built-in validation rules exists and unique. It uses Eloquent models instead of directly querying the database.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors 4

  •  
  •  
  •  
  •