Home > OS >  Laravel only add alpha_num if certain conditoin is meet
Laravel only add alpha_num if certain conditoin is meet

Time:09-07

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';
}

CodePudding user response:

use Illuminate\Validation\Rule;

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