How to generate PHP enums from database in Laravel?

Richard Dobroň
2 min readJul 14, 2022

--

A magic number is a configuration parameter typed as a number in the middle of some code.

And that magic number is a bad thing.

Using this library, you will fix the following code:

To such:

How to use this generator?

First of all, install composer laravel-db-enum-generator package:

composer require dobron/laravel-db-enum-generator

Let’s say the user_roles database table has the following structure:

user_roles table data

Now call artisan command make:enum.

# with laravel model
php artisan make:enum UserRoleTypes — model=UserRole — id=Id — slug=Slug — title=Role
# with laravel model that does not have slug column (will be auto-generated from — title)
php artisan make:enum UserRoleTypes — model=UserRole — id=Id — title=Role
# with database table
php artisan make:enum UserRoleTypes — table=user_roles — id=Id — slug=Slug — title=Role
# etc.

The UserRoleTypes.php file was generated in the ./app/enums/ directory.
If you update the database table, just use the same command with the --force flag to overwrite the file.

How to find magic numbers in the project?

I recommend using a library called PHPMND.

This stands for PHP Magic Number Detector.

A detailed installation guide can be found at https://github.com/povils/phpmnd

But if you’re using Composer, here’s how you can install it quickly:

composer require --dev povils/phpmnd

Once that’s done, you run it like this:

phpmnd .

--

--