mpen mpen - 1 year ago 252
PHP Question

Where to put/how to handle enums in Laravel?

Laravel has a

form helper which takes as input a dictionary. I like to keep the values for all of these in a central place. For example, I might have an enum that looks like this:

$phoneTypes = [
'CELL' => "Cellular",
'HOME' => "Home",
'WORK' => "Work",

Which I want to use in both my view/template, and in the database:

Schema::create('customers', function (Blueprint $table) {

  1. Is there a recommended place to put these?

  2. Can I make them global so I can access them easily in all my views?

Answer Source

Personally I'd avoid an enum DB column type altogether. Database enum column types can be problematic, see here for one article on this topic.

Handling enums in the DB

If you want to manage your list in the database, I'd create a separate phone_types database table and create a relationship with your customers table.

Handling enums in your code

It's also quite easy to manage your enums in code, and avoid the DB completely.

Since you're using Laravel, I think setting up a config file would be a viable option.

Say you create a new file config/enums.php with the following:

return [
    'phone_types' => [
        'CELL' => "Cellular",
        'HOME' => "Home",
        'WORK' => "Work",

You can now hand that off to the form helper quite easily:

Form::select('phone', Config::get('enums.phone_types'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download