Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation exists where NOT

Based on the documentations. Exists can have 4 parameters:

exists:table,id,where,0

The question is, What if I wanted it to be where is not. Like where is not 0.

$validator = Validator::make(
    array(
        'groups' => $groups
    ),
    array(
        'groups' => 'required|exists:groups,jid,parent,!=,0'
    )
);
like image 788
majidarif Avatar asked Dec 26 '13 13:12

majidarif


3 Answers

You can use something like this:

Validator::extend('not_exists', function($attribute, $value, $parameters)
{
    return DB::table($parameters[0])
        ->where($parameters[1], '=', $value)
        ->andWhere($parameters[2], '<>', $value)
        ->count()<1;
});
like image 22
Vladislav Rastrusny Avatar answered Nov 20 '22 04:11

Vladislav Rastrusny


You can use unique

Example

'email' => 'unique:users,email_address,NULL,id,account_id,1'

In the rule above, only rows with an account_id of 1 would be included in the unique check.

http://laravel.com/docs/4.2/validation#rule-unique

like image 122
Cas Bloem Avatar answered Nov 20 '22 04:11

Cas Bloem


With Laravel 5.2 or later you can prepend the values to be checked against with a !:

'groups' => 'required|exists:groups,jid,parent,!0'

The same login goes for unique, only you need the extra parameters:

'groups' => 'required|unique:groups,jid,NULL,id,parent,!0'
like image 8
Tomas Buteler Avatar answered Nov 20 '22 06:11

Tomas Buteler