This is the first practical example I've seen. I tried looking up enums and what they're used for, but most sites and examples keep it very abstract and technical. I'm also glad you've voiced the same opinion I've had since I first heard about enums: why not just put those values in the database...
I do like the latter variant - to have model-related constants in the model itself. It is way easier to navigate and understand, also it is not hard to reference in other places.
Thanks a lot for the video .. I used to use enum but after watching your enum video I started using foreign keys for tables ... much easier to use throughout the project...
Another great video! I had previously been taking a similar enum approach to how Laravel handles it in 8.1 by using an Enum package from Ben Sampo. Interesting that this is now native in Laravel!
You can use both enums and foreign keys. Sometimes you need to handle specific task for a given value. And instead of hardcoding the value, we use enums to avoid writing mistakes. Also the IDE will help you list all the values
Totally agreed, spécial for Api, lots api need to return exact enum and it's need to sync with front otherwise only Api will be not working, but also true it will more faster to use enum
For almost every constant values I use DB as well, except for some small enum arrays that most likely will never change, like gender. I don't make a seperate table for that, but use enums. 0 => 'female', 1 => 'male'. This way I only store 0 or 1 in the users table en get the value from the enums when I need to display the gender. null is the default value in the migration, when users don't submit their gender.
I usually use this frequently in a different way. I create a namespace called Enums. Create a class, for example, TicketStatus. In TIcketStatus class, there will be 2 constants. public const OPEN = 1; public const CLOSE = 0; If a different type of constant is needed, I will create another class and define the constant there. It's far clear to me and it surely throws early errors/exceptions to fix. This is what I did as "fake enum" from past, when enum is not in php. At last, as you said you use foreign key and integer field, I also prefer so and the solution I use here, helps in that case too.
Lately i was reading Elegant Objects - and kind of agree with it that if you have constants in your code - it feels kind of fishy, yea maybe in some places it makes sense. But in many other cases you should create separate class or even interface(and then you can easly switch implementation to something else).
I actually prefer both ways: Database Foreign Keys so it is extensible + separate Enum class for greater static analysis in case there are special/specific cases in the business logic for any of the values in the foreign key That way I can check if ($ticket->status == TicketStatus::open->value) { // something } but also add new values via database
Personally, I use constants extensively especially for strings that are used multiple times in the project. PhpStorm indexes these and allows it to suggest matches in the auto-complete feature meaning that I am much less likely to have invalid strings. For example, "ROUTE_PROJECT_INDEX" is defined as "project.index" and all my routes names are defined this way. PhpStorm will auto suggest the ROUTE_PROJECT_INDEX constant but not the 'project.index' string. So, routes, ACL entires, SQL commands and so on. This is in addition to constants as shown in your video. Not sure about enums yet, they are too new.
There are spatie/enum and for more advanced usage spatie/laravel-model-states packages. I never use enums, since to me it is sort of code smell. Sooner or later you start using something else with that status 'closed' or status 'sent', why wouldn't you just make it OOP way and create classes for each enum/state. It's much more configurable, much more flexible, and much easier to use. And if you want to add some parameter to your enum, you simply add a new class, instead of touching already working code (letter 'O' in SOLID).
I don't like writting the status in database level because even if a new status is added or updated, you will still need to come to the source code to update its usage. So unless status is a bigger deal than the use case here (which is often the use case in production), there is no point moving that overhead to the database. So Enums or Constants is fine. I will go with Enum for closeness to future features as you stated.
Honestly I have never really considered a new table to store possible values except in cases where I intend to provide a CRUD interface to allow the user to customize those values on the fly. tbh I always just did a DB level enum and a constant in the related model. I was considering upgrading to 8.1 then refactoring to a php enum and a tinyint filed in the DB but I think I may instead opt for your method.
Thanx, I have also found it easier to use a database so that whenever something changes, one could add/remove/edit from the database level itself. I mean, the only constant is change itself. Even gender has changed 😉
Having constants like the source code where a constant is an array it kinda beats the purpose of a constant. Instead TICKETS_ISSUE_OPEN = ‘open’ is more descriptive and eliminates the need to look the Constant class all the time
Great tutorial ! I tried to localise enums as in your video, I add this to my languages file but it's not working : 'status' =>[ ExpenseStatus::Paid->name => 'Payée', ExpenseStatus::Validated->name => 'Validée', ExpenseStatus::OnHold->name => 'En attente', ExpenseStatus::Waiting->name => 'A valider', ], Any idea ? Tks :)
Hi Do anyone has idea about how serialize the Enum when retrieving from DB for API response or toArray/Json methods. For me unless I interact with field cased it will show the just the value in DB but after interact I can call method value/name enum OrderStatusEnum: int { case Open = 0; case Closed = 1; } protected $casts = [ 'status' => OrderStatusEnum::class, ]; Model::get()->toArray() "status" => 1 I want "status" => [ "name" => "Open", "value"=> 1]
I strongly disagree pretty much on everything you’ve said. Storing “enum like” values in dictionary table is anti pattern, especially when changes of the enum values saved on a record are used to trigger some logic. There is a reason why enums are read-only. Let’s say that you keep in db all your enums including enum for OrderStatus. Depending on change of OrderStatus different things happen in your code. When status is set to PARCEL_AWAITING_COLLECTION, then email containing tracking number is sent to the customer. When status of the order changes to REFUNDED, then money are transferred out of your account to customers account. New employee changes by accident enum values in dictionary table leaving translations unchanged. And now something that is displayed as “Parcel Awaiting Collection” on order actually issues a refund. In best case scenario you will lose fees for issuing refunds. You said that at any point you can add new values table in db, which is right, but only if those values have only informational purposes and are displayed on screen and do nothing else. If your app is multilingual you will most likely have to generate some lang / po files anyways or store translations in db - which is also cumbersome - translators will not have an access to your db. Etc, etc, etc. Btw in that “fixed” code from video a strict comparison should be used.
This is the first practical example I've seen. I tried looking up enums and what they're used for, but most sites and examples keep it very abstract and technical. I'm also glad you've voiced the same opinion I've had since I first heard about enums: why not just put those values in the database...
I do like the latter variant - to have model-related constants in the model itself. It is way easier to navigate and understand, also it is not hard to reference in other places.
Thanks a lot for the video .. I used to use enum but after watching your enum video I started using foreign keys for tables ... much easier to use throughout the project...
Another great video! I had previously been taking a similar enum approach to how Laravel handles it in 8.1 by using an Enum package from Ben Sampo. Interesting that this is now native in Laravel!
You can use both enums and foreign keys. Sometimes you need to handle specific task for a given value. And instead of hardcoding the value, we use enums to avoid writing mistakes. Also the IDE will help you list all the values
Totally agreed, spécial for Api, lots api need to return exact enum and it's need to sync with front otherwise only Api will be not working, but also true it will more faster to use enum
For almost every constant values I use DB as well, except for some small enum arrays that most likely will never change, like gender. I don't make a seperate table for that, but use enums. 0 => 'female', 1 => 'male'. This way I only store 0 or 1 in the users table en get the value from the enums when I need to display the gender. null is the default value in the migration, when users don't submit their gender.
I usually use this frequently in a different way.
I create a namespace called Enums.
Create a class, for example, TicketStatus.
In TIcketStatus class, there will be 2 constants.
public const OPEN = 1;
public const CLOSE = 0;
If a different type of constant is needed, I will create another class and define the constant there.
It's far clear to me and it surely throws early errors/exceptions to fix.
This is what I did as "fake enum" from past, when enum is not in php.
At last, as you said you use foreign key and integer field, I also prefer so and the solution I use here, helps in that case too.
Lately i was reading Elegant Objects - and kind of agree with it that if you have constants in your code - it feels kind of fishy, yea maybe in some places it makes sense. But in many other cases you should create separate class or even interface(and then you can easly switch implementation to something else).
Great video! I prefer to code constants in the related models o services. If required by a change of functionality I move to database.
As mentioned by you, if the enums are not static then it is better to use foreign keys and this is what we currently use.
I actually prefer both ways: Database Foreign Keys so it is extensible + separate Enum class for greater static analysis in case there are special/specific cases in the business logic for any of the values in the foreign key
That way I can check if ($ticket->status == TicketStatus::open->value) { // something }
but also add new values via database
Personally, I use constants extensively especially for strings that are used multiple times in the project. PhpStorm indexes these and allows it to suggest matches in the auto-complete feature meaning that I am much less likely to have invalid strings.
For example, "ROUTE_PROJECT_INDEX" is defined as "project.index" and all my routes names are defined this way. PhpStorm will auto suggest the ROUTE_PROJECT_INDEX constant but not the 'project.index' string. So, routes, ACL entires, SQL commands and so on.
This is in addition to constants as shown in your video.
Not sure about enums yet, they are too new.
Obrigado pelo conteúdo !
There are spatie/enum and for more advanced usage spatie/laravel-model-states packages.
I never use enums, since to me it is sort of code smell. Sooner or later you start using something else with that status 'closed' or status 'sent', why wouldn't you just make it OOP way and create classes for each enum/state. It's much more configurable, much more flexible, and much easier to use. And if you want to add some parameter to your enum, you simply add a new class, instead of touching already working code (letter 'O' in SOLID).
I don't like writting the status in database level because even if a new status is added or updated, you will still need to come to the source code to update its usage. So unless status is a bigger deal than the use case here (which is often the use case in production), there is no point moving that overhead to the database. So Enums or Constants is fine. I will go with Enum for closeness to future features as you stated.
Best RUclipsr for me ❤
If the code-table is more or less fixed then it is excellent solution.
Thanks a lot for the video
Honestly I have never really considered a new table to store possible values except in cases where I intend to provide a CRUD interface to allow the user to customize those values on the fly. tbh I always just did a DB level enum and a constant in the related model. I was considering upgrading to 8.1 then refactoring to a php enum and a tinyint filed in the DB but I think I may instead opt for your method.
Please make a new video on how you use the foreign keys logic
Thanx, I have also found it easier to use a database so that whenever something changes, one could add/remove/edit from the database level itself. I mean, the only constant is change itself. Even gender has changed 😉
Having constants like the source code where a constant is an array it kinda beats the purpose of a constant. Instead TICKETS_ISSUE_OPEN = ‘open’ is more descriptive and eliminates the need to look the Constant class all the time
Totally agree. Constants should be used, in it's nature, to better readability and as the name says, constant values.
Great tutorial !
I tried to localise enums as in your video, I add this to my languages file but it's not working :
'status' =>[
ExpenseStatus::Paid->name => 'Payée',
ExpenseStatus::Validated->name => 'Validée',
ExpenseStatus::OnHold->name => 'En attente',
ExpenseStatus::Waiting->name => 'A valider',
],
Any idea ?
Tks :)
database all day everyday 24/7 it is dynamic and modifications are mostly straight forward
would it be possible to make a video about fullcalendar mainly about drop events from a list from the database to the calendar...thanks
i usually store constants in a seperate config file. and then access them with Config::get(const_name )
how can use unique validation for 3 column like (firstname , middlename , lastname )
Custom validation rule
implementation of the Apriori algorithm in laravel, can you give an example of this?
Never done it myself
@@LaravelDaily as a newbie in laravel, i'm confused😶
Hi
Do anyone has idea about how serialize the Enum when retrieving from DB for API response or toArray/Json methods.
For me unless I interact with field cased it will show the just the value in DB but after interact I can call method value/name
enum OrderStatusEnum: int
{
case Open = 0;
case Closed = 1;
}
protected $casts = [
'status' => OrderStatusEnum::class,
];
Model::get()->toArray()
"status" => 1
I want "status" => [ "name" => "Open", "value"=> 1]
me too, I prefered to use DB for const, status, tickets etc.
Database is my choice.
I strongly disagree pretty much on everything you’ve said. Storing “enum like” values in dictionary table is anti pattern, especially when changes of the enum values saved on a record are used to trigger some logic. There is a reason why enums are read-only.
Let’s say that you keep in db all your enums including enum for OrderStatus. Depending on change of OrderStatus different things happen in your code. When status is set to PARCEL_AWAITING_COLLECTION, then email containing tracking number is sent to the customer. When status of the order changes to REFUNDED, then money are transferred out of your account to customers account. New employee changes by accident enum values in dictionary table leaving translations unchanged. And now something that is displayed as “Parcel Awaiting Collection” on order actually issues a refund. In best case scenario you will lose fees for issuing refunds.
You said that at any point you can add new values table in db, which is right, but only if those values have only informational purposes and are displayed on screen and do nothing else.
If your app is multilingual you will most likely have to generate some lang / po files anyways or store translations in db - which is also cumbersome - translators will not have an access to your db.
Etc, etc, etc.
Btw in that “fixed” code from video a strict comparison should be used.