Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

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

0 likes
16 replies
MichalOravec's avatar

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

martinbean's avatar

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'))
vincent15000's avatar

Thank you.

Once again I get the same error.

Rule::unique('budgets')->ignore($this->budget->id),
martinbean's avatar

@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.

vincent15000's avatar

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.

vincent15000's avatar

With the resource.

Route::resource('budgets', BudgetController::class);
MichalOravec's avatar
Level 75

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)
vincent15000's avatar

Ok thank you it works, I didn't understand that I had to add ->ignore() after the ->where().

vincent15000's avatar

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 ?

MichalOravec's avatar

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.

1 like

Please or to participate in this conversation.