web-dev-qa-db-ja.com

Laravel検証が存在しない場所に存在します

documentations に基づいています。 Existsには4つのパラメーターがあります。

exists:table,id,where,0

問題は、どこにないようにしたいのかです。どこが0ではないように。

$validator = Validator::make(
    array(
        'groups' => $groups
    ),
    array(
        'groups' => 'required|exists:groups,jid,parent,!=,0'
    )
);
16
majidarif

次のようなものを使用できます。

Validator::extend('not_exists', function($attribute, $value, $parameters)
{
    return DB::table($parameters[0])
        ->where($parameters[1], '=', $value)
        ->andWhere($parameters[2], '<>', $value)
        ->count()<1;
});
13

uniqueを使用できます

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

上記のルールでは、account_idが1の行のみが一意のチェックに含まれます。

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

36
Cas Bloem

Laravel 5.2以降では、チェックする値の前に!を付けることができます。

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

同じログインがuniqueにも当てはまりますが、追加のパラメーターが必要なだけです。

'groups' => 'required|unique:groups,jid,NULL,id,parent,!0'
6
Tomas Buteler

「not 0」を探しているのは知っていますが、参考のためにNOT_NULL、次のように:

'groups' => 'required|exists:groups,jid,parent,NOT_NULL'

現時点ではドキュメントに記載されていませんが、 これについての議論があります(最後の投稿を参照)

1

カスタムバリデーターはこちら

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

使用例:

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

次のようにデフォルト値を渡すことができます:

model_type;App\User
0
Buraco