Laravel validation exists where NOT

Viewed 46905

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'
    )
);
6 Answers

A custom validator is here

Validator::extend('not_exists', function($attribute, $value, $parameters, $validator)
{
    $table = array_shift($parameters);
    $db    = \DB::table($table);

    foreach ($parameters as $parameter)
    {
        $check = explode(';', $parameter);
        $col   = array_shift($check);
        $value = array_get($check, 0, array_get($validator->getData(), $col, false));

        $db->where($col, $value);
    }

    return $db->count() < 1;
});   

Example usage:

not_exists:model_has_roles,role_id,model_type;App\User,model_id

You can pass default value like this:

model_type;App\User

maybe you can try <> 0 ,that's the SQL for not equal

Related