Skip to content
Advertisement

Laravel form validation using where clause

I’m working on a small project using Laravel and everything is ok with me just i would like to know how can i add a where clause in my validation rule this my code :

public function rules()
{
    return [
        'number' => 'required|integer|unique:apartments,number',
    ];
}

i have a table called peoples, contain 3 fields (id, number, room)

how i can add a where clause including room field,  where number is  unique and room != 5, 

Advertisement

Answer

If you using Laravel 7 you can handle it like this

use IlluminateValidationRule;

public function rules()
{
    return [
        'number' => [
            'required',
            'integer',
            Rule::unique('apartments', 'number')->where(function ($query) {
                return $query->where('room', '!=', 5);
            })
        ]
    ];
}

Source

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement