Cudos
Cudos

Reputation: 5894

Laravel only add alpha_num if certain conditoin is meet

How can I only add alpha_num to the validation if $this->language() returns en?

public function rules()
{
    return [
        'title' => ['required', 'alpha_num'],
    ];
}

public function language()
{
    // For brevity I only return "en", it could be other languages
    return 'en';
}

Upvotes: 0

Views: 34

Answers (1)

JS TECH
JS TECH

Reputation: 1583

use Illuminate\Validation\Rule;

public function rules()
{
    return [
        'title' => ['required', Rule::when($this->language() === 'en', ['alpha_num'])],
    ]; 
}

Upvotes: 2

Related Questions