mafortis
mafortis

Reputation: 7128

Can we set laravel enum column to be unique

Can enum column be unique?

I have 5 different currencies in my table and only one of them has to be default, can i set unique for that column?

$table->enum('default_currency', ['yes', 'no'])->unique();

Upvotes: 0

Views: 275

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

No, you can't do using UNIQUE INDEX. It will work for two rows, but in the third row it will fail, since the valid values are just two.

You need to manually do this logic, and you can do it in many places. I personally like to do this kind of logic in a model observer, so you can watch the saving event. The logic is this:

  1. Something try to save the currency (create or update)
  2. The model observer will catch the saving event
  3. If the default_currency is set to true, you do some query like this: Currency::whereDefaultCurrency(true)->update(["default_currency"=>false])

Thia way, you will always have one single currency with default_currency set to true.

Example of CurrencyObserver:

class CurrencyObserver {
    public function saving(Currency $currency) {
        if ($currency->isDirty('default_currency') && $currency->default_currency) {
            Currency::where('default_currency', true)->update(['default_currency' => false]);
        }

        return true;
    }
}

Upvotes: 2

Related Questions