Complex unique rule in the request form ? Hello,
I have to add annual budgets to clients.
return [
'year' => [
'required',
'integer',
Rule::unique('budgets')
->where('year', $this->year)
->where('client_id', $this->client_id)
],
'amount' => 'numeric|nullable',
];
But when I have to edit the budget, it tells me that there's already a budget for this year.
How can I solve this ?
Thanks a lot ;).
V
Thank you @michaloravec and @martinbean ? i had just tried it but it doesn't work.
Rule::unique('budgets')->ignore($this->budget->year),
I get the same error.
You have to ignore the id of budgets table
The same id hat you have in url.
You get it with $this->route('budget')->id
Because you didn’t read the docs properly. You pass a model or primary key to the ignore method; not a random attribute.
You’ll need to combine the ignore method with your existing where clauses:
Rule::unique('budgets')
->where('year', $this->year)
->where('client_id', $this->client_id)
->ignore($this->route('budget'))
Thank you.
Once again I get the same error.
Rule::unique('budgets')->ignore($this->budget->id),
What is your route for update?
@vincent15000 So check the value of $this->budget->id and ensure you’re actually passing the value you’re expecting to be passed to that method.
I use the good id value to update the budget.
Here is my update route : http://localhost:8000/budgets/2055/edit .
What has to be unique is the couple (client_id, year). There can be only one annual budget per client, but there are several budgets with the same year, each one with a different client.
With the resource.
Route::resource('budgets', BudgetController::class);
So paramater is budget.
How I said above it has to be
Rule::unique('budgets')
->where('year', $this->year)
->where('client_id', $this->client_id)
->ignore($this->route('budget')->id)
Ok thank you it works, I didn't understand that I had to add ->ignore() after the ->where().
Could you please tell me what's better between $id = $this->budget ? $this->budget->id : null; then using $id and $this->route('budget')->id ? I think it's equivalent isn't it ?
Imagine that you have
<input type="text" name="budget">
then you have a problem, or somebody just change name attribute to budget, you have a problem as well.
With $this->route('budget')->id it never happen.
Please sign in or create an account to participate in this conversation.