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.
Advantages
- The rule can be easily extended with the Eloquent builder. (scopes etc.)
- Softdeletes are working out of the box.
- Logic implemented into the models work in the validation as well. (multi tenancy system, etc.)
You can install the package via composer with following command:
composer require korridor/laravel-model-validation-rules
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"
This package is tested for the following Laravel versions:
- 6.0
- 5.8
- 5.7 (stable only)
- 5.6 (stable only)
PostStoreRequest
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
// ...
public function rules()
{
$postId = $this->post->id;
return [
'username' => [new UniqueEloquent(User::class, 'username')],
'title' => ['string'],
'content' => ['string'],
'comments.*.id' => [
'nullable',
new ExistsEloquent(Comment::class, null, function (Builder $builder) use ($postId) {
return $builder->where('post_id', $postId);
}),
],
'comments.*.content' => ['string']
];
}
PostUpdateRequest
use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
// ...
public function rules()
{
$postId = $this->post->id;
return [
'id' => [new ExistsEloquent(Post::class)],
'username' => [new UniqueEloquent(User::class, 'username')->ignore($postId)],
'title' => ['string'],
'content' => ['string'],
'comments.*.id' => [
'nullable',
new ExistsEloquent(Comment::class, null, function (Builder $builder) use ($postId) {
return $builder->where('post_id', $postId);
}),
],
'comments.*.content' => ['string']
];
}
I am open for suggestions and contributions. Just create an issue or a pull request.
composer test
composer test-coverage
composer fix
composer lint
The structure of the repository and the TestClass is inspired by the project laravel-validation-rules by spatie.
This package is licensed under the MIT License (MIT). Please see license file for more information.