majidarif
majidarif

Reputation: 19985

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

Upvotes: 23

Views: 62434

Answers (6)

Buraco
Buraco

Reputation: 461

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

Upvotes: 0

Giaken
Giaken

Reputation: 1

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

Upvotes: -2

Tomas Buteler
Tomas Buteler

Reputation: 4117

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'

Upvotes: 11

Captain Hypertext
Captain Hypertext

Reputation: 2506

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)

Upvotes: 2

Cas Bloem
Cas Bloem

Reputation: 5040

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

Upvotes: 54

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29975

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

Upvotes: 14

Related Questions