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

Armani's avatar
Level 17

Check uniqueness before inserting a new record

I'm using Select2 in my project and enabled Tags feature that can be used to add option on the fly. I also use FormRequest, I made the logic to create new item in the lookup table if user used tags feature, everything works fine but the only problem is that I want to make sure the new item is unique in the database.

public function rules()
    {
        return [
            'unit_id' => 'required',
        ];
    }
public function prepareForValidation()
    {
        $this->merge(
            [
                'unit_id' => is_numeric($this->unit_id)  ?  $this->unit_id  :  Unit::create(['name' => $this->unit_id])->id,
            ]
        );
    }
0 likes
1 reply
tisuchi's avatar
tisuchi
Best Answer
Level 70

@armani Like this?

public function rules()
    {
        return [
            'unit_id' => [
                'required', 
                Rule::unique('units')->where(function ($query) {
                    return $query->where('name', $this->unit_id);
                }),
            ],
        ];
    }

public function prepareForValidation()
    {
        $this->merge(
            [
                'unit_id' => is_numeric($this->unit_id) ? $this->unit_id : 
                            Unit::firstOrCreate(['name' => $this->unit_id])->id,
            ]
        );
    }

1 like

Please or to participate in this conversation.