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

vincent15000's avatar

Validation unique on two columns in a form request

Hello,

I have a form request to validate the datas.

public function rules(): array
{
    return [
        'branch_id' => 'required|integer|exists:branches,id',
        'user_id' => 'required|integer|exists:users,id',
        'role_id' => 'required|integer|exists:roles,id',
    ];
}

In the database, I have added a unique key on twoi columns.

$table->unique(['branch_id', 'user_id']);

How can I modify my rules to take the uniqueness for the couple of fields (branch_id, user_id) ?

Thanks for your help.

V

0 likes
2 replies
LaryAI's avatar
Level 58

To enforce the unique constraint on the combination of branch_id and user_id in your validation rules, you can use the unique validation rule with additional parameters to specify the table and the columns that need to be unique together. Here's how you can modify your rules method to include this validation:

public function rules(): array
{
    return [
        'branch_id' => [
            'required',
            'integer',
            'exists:branches,id',
            Rule::unique('your_table_name')->where(function ($query) {
                return $query->where('user_id', $this->user_id);
            }),
        ],
        'user_id' => 'required|integer|exists:users,id',
        'role_id' => 'required|integer|exists:roles,id',
    ];
}

In this example, replace your_table_name with the actual name of the table where the unique constraint is defined. The Rule::unique method is used to specify a custom query for the unique validation rule. The where closure is used to add an additional condition to the unique rule, ensuring that the combination of branch_id and user_id is unique.

Make sure to include the necessary namespace for the Rule facade at the top of your form request file:

use Illuminate\Validation\Rule;

This solution assumes that you are using Laravel's form request validation. If the branch_id and user_id are being updated, you may need to exclude the current record from the unique check. You can do this by passing the ID of the current record to the ignore method on the Rule object.

s4muel's avatar
s4muel
Best Answer
Level 50

use the where clause in the unique rule ("Adding Additional Where Clauses", last header in https://laravel.com/docs/11.x/validation#rule-unique)

public function rules(): array
{
    return [
        'branch_id' => 'required|integer|exists:branches,id',
        'user_id' => ['required', 'integer', 'exists:users,id', Rule::unique('your_model_table')->where(fn (Builder $query) => $query->where('branch_id', $request->branch_id))], //or $this->branch_id when in form request context
        'role_id' => 'required|integer|exists:roles,id',
    ];
}
1 like

Please or to participate in this conversation.