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

caje731's avatar

Restricting column values while creating a table using migration

Hi,

I'm trying to create a table using a migration, and I would like to restrict values of a column 'operation_type' to either of 'update', 'create', 'delete' . Can this be done while defining the migration? More importantly, is this the right way of restricting values ?

0 likes
5 replies
mstnorris's avatar

Why would you not want to do it in the DB? Surely having it at the Database level will absolutely not allow any other values. Just like setting unique on a table prevents multiple occurrences of the same value.

I'd still do it at the code level too, but why not both?

JarekTkaczyk's avatar

@mstnorris Because most likely db is treated somewhat as a static (in terms of the schema) storage. Once setup, it rather does not change. However the needs of your app may change, and you reflect the change in your logic.

That said, you need to alter the behaviour of the app, but do not need to touch the db.

This is matter of preference and needs. I would say it depends on the way an application is developed and how big/complex it is. If you need that additional layer of control, then use both, but mind that you also need to take care of the errors handling then (unique, enum, fk or other constraints)

1 like
abrookes's avatar

@bahuzi I would suggest using a mutator:

    // restrict the user_type attribute to only 'user' or 'admin'
    public function setUserTypeAttribute($value)
    {
        $this->attributes['user_type'] = in_array($value, ['user', 'admin']) ? $value : 'user';
    }

(works in laravel 9)

Please or to participate in this conversation.