cover-img

How to generate PHP enums from database in Laravel?

14 July, 2022

3

3

0

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 package:


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

IdSlugRole
1MANAGERAdmin
2CONTENT_CREATOREditor
3MODERATORModerator
4ADVERTISERAdvertiser
5INSIGHTS_ANALYSTAnalyst

Now call artisan command make:enum.


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:


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

tutorial

php

laravel

automation

artisan

3

3

0

tutorial

php

laravel

automation

artisan

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.