PHP code example of korridor / laravel-model-validation-rules

1. Go to this page and download the library: Download korridor/laravel-model-validation-rules 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/ */

    

korridor / laravel-model-validation-rules example snippets


use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
// ...
public function rules(): array
{
    $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']
    ];
}

use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
// ...
public function rules(): array
{
    $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']
    ];
}

use Korridor\LaravelModelValidationRules\Rules\UniqueEloquent;
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
// ...
public function rules(): array
{
    $postId = $this->post->id;
    
    return [
        'id' => [(new ExistsEloquent(Post::class))->withMessage('The ID already exists.')],
        'username' => [
            (new UniqueEloquent(User::class, 'username'))
                ->ignore($postId)
                ->withCustomTranslation('validation.custom.username.unique_eloquent')
        ],
        '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']
    ];
}

return [
    'exists_model' => 'A :model with the :attribute ":value" does not exist.',
    'unique_model' => 'A :model with the :attribute ":value" already exists.',
];
bash
php artisan vendor:publish --provider="Korridor\LaravelModelValidationRules\ModelValidationServiceProvider"