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.
public static $rules = 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,:cause_id',
);
And then in my controller I run:
$input = array(
'amount' => Input::get('amount'),
'user_id' => $this->currentUser->id,
'cause_id' => $cause->id,
'circle_id' => Input::get('circle_id')
);
$validator = Validator::make($input, Donation::$rules);
How can I get the cause_id in the validation rule without concatenating it? As you can see by the rules array, I have tried the PDO style :placeholder, but the query is executed as:
select count(*) as aggregate from donations where circle_id = '500' and cause_id = ':cause_id'
The Laravel documentation on validation has a sub-section titled, “Adding Additional Where Clauses” in the unique rule section:
Unfortunately you will have to concatenate a variable value if you want it passed as part of the conditions:
Or you make it more readable by specifying validation rules as an array:
My suggestion in your case would be to wrap your rules in a function:
And then call your function, passing in your value:
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.
in Laravel 5, your "public function rules()" is supposed to be in your FormRequest object:
Defined my own class, so the existing rules declared in the class can stay.
Then added a magic method for Laravel:
In the service provider boot method:
Then added the class to src folder for package:
I did try and simply append my method to the existing unique method, but as they are in different class spaces, it was causing issues with Laravel's native methods: