PHP code example of spatie / laravel-validation-rules

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

    

spatie / laravel-validation-rules example snippets


class ModelPolicy
{
    use HandlesAuthorization;

    public function edit(User $user, Model $model): bool
    {
        return $model->user->id === $user->id;
    }
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Authorized;

public function rules()
{
    return [
        'model_id' => [new Authorized('edit', TestModel::class)],
    ];
}

new Authorized('edit', TestModel::class, 'guard-name')

// in a `FormRequest`

use Spatie\ValidationRules\Rules\CountryCode;

public function rules()
{
    return [
        'country_code' => ['

// in a `FormRequest`

use Spatie\ValidationRules\Rules\CountryCode;

public function rules()
{
    return [
        'country_code' => [(new CountryCode())->nullable()],
    ];
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Currency;

public function rules()
{
    return [
        'currency' => ['

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Currency;

public function rules()
{
    return [
        'currency' => [new Currency()], // This will pass for any valid currency, an empty value or null
    ];
}

class UserRole extends MyCLabs\Enum\Enum
{
    const ADMIN = 'admin';
    const REVIEWER = 'reviewer';
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Enum;

public function rules()
{
    return [
        'role' => [new Enum(UserRole::class)],
    ];
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\ModelsExist;

public function rules()
{
    return [
        'model_ids' => ['array', new ModelsExist(Model::class)],
    ];
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\ModelsExist;

public function rules()
{
    return [
        'user_emails' => ['array', new ModelsExist(User::class, 'emails')],
    ];
}

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email')],
    ];
}

(new Delimited('email'))->min(2)

(new Delimited('email'))->max(2)

(new Delimited('numeric'))->allowDuplicates()

(new Delimited('email'))->separatedBy(';')

(new Delimited('email'))->doNotTrimItems()

new Delimited('email|max:20')

// in a `FormRequest`

use Spatie\ValidationRules\Rules\Delimited;

public function rules()
{
    return [
        'emails' => [new Delimited('email', $this->messages())],
    ];
}

public function messages()
{
    return [
        'emails.email' => 'Not all the given e-mails are valid.',
    ];
}
bash
php artisan vendor:publish --provider="Spatie\ValidationRules\ValidationRulesServiceProvider"