Laravel 5 Validation unique pass variable placeholder

前端 未结 4 1848
时光说笑
时光说笑 2021-02-09 20:42

Is it possible to pass the unique validation method extra where clauses with a variable?

Heres an example:

In my model I have my validation rules.



        
4条回答
  •  [愿得一人]
    2021-02-09 21:14

    My suggestion in your case would be to wrap your rules in a function:

    public static function rules($causeId)
    {
        return array(
            'amount'    => 'required|numeric',
            'user_id'   => 'required|exists:users,id',
            'cause_id'  => 'required|exists:causes,id',
            'circle_id' => 'required|unique:donations,circle_id,NULL,id,cause_id,' . $causeId,
        );
    }
    

    And then call your function, passing in your value:

    $validator = Validator::make($input, Donation::rules($yourCauseId));
    

    I've had problems like this in the past, I've also wanted to use the values from other fields, in the rule for another field too. This tends to be the easiest way to get around it.

提交回复
热议问题