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. Lik
maybe you can try <> 0
,that's the SQL for not equal
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;
});
I know you're looking for 'not 0', but for reference sake, you can use NOT_NULL
, as in:
'groups' => 'required|exists:groups,jid,parent,NOT_NULL'
It's not listed in the docs right now, but here is the discussion about it (see very last post)
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
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'
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