Skip to content
Advertisement

Laravel – Where to store statuses (flags)? Model, Class or config folder?

I need to extensively use statuses in mt project. I need them for my users (active, suspended, etc), an entity (active, pending_activation, inactive) and for my subscriptions(active, on_grace_period, not_subscribed, never_subscribed).

So far I thought that the best way is to store them in the DB but i have a feeling it’s much easier to have them in the other 3 options.

I also thought that i can store them in my Eloquent Model as constants. For example my subscription model would look like this:

JavaScript

and retrieving them, for example in a blade view:

JavaScript

How about doing the same but using the config folder and adding a file called status.php. Accessing it in the view would be like:

JavaScript

Is there a better way?

Also, how about the other part of the equation, meaning the status stored in the DB. Should I only have a status column for the subscription table and store what the app dictates or even bettter create a separate table subscription_statuses and have a foreign_key subscription_status_id in the subscriptions table?

Advertisement

Answer

I tend to create a specific model for statuses, that acts as an enum. So if I have an Event model, I may have a corresponding EventStatus model that looks like this:

JavaScript

I can then do checks like this:

JavaScript

And I’ll usually add convenience methods to my models too:

JavaScript

For the “human-friendly” strings, I’ll then have a language file that has the text strings:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement