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

Wakanda's avatar
Level 10

Make code field unique only if has different years in dates

Hi Devs,

I have a table with the code and date

Table

$table->string('code')->nullable();
$table->date('date')->nullable();

code is unique yearly but not unique if the code is in the same year.

I want to validate this how can I handle such a scenario.

0 likes
1 reply
sr57's avatar

You should be able to create your own rule "UniqCodePerYear"

use this doc

https://laravel.com/docs/9.x/validation#using-rule-objects

to define the rule and access all the data

and your validation can be st like this

$count = DB::table('my_table')->where('code', $value)
                            ->where('year', $data->year)
                            ->count();

return $count === 0;

or you change your db use a field code_year.

1 like

Please or to participate in this conversation.