No video

Enum PHP 8.1 Classes in Laravel: Practical Example

In the new PHP 8.1 version, you can use Enum classes. How would they work in Laravel? Let me show you an example.
Full repository: github.com/Lar...
Link to the Enum Pull Request: github.com/Lar...
PHP 8.1 Enums: stitcher.io/bl...
Enum casting in Laravel: laravel.com/do...
Twitter discussion about Enums: / 1468922708457136131
- - - - -
Support the channel by checking out premium products:
- Enroll in my Laravel courses: laraveldaily.t...
- Try our Laravel QuickAdminPanel: bit.ly/quickad...
- Buy my ready-made Laravel scripts: laraveldaily.g...
- Purchase my Livewire Kit: livewirekit.com
- Subscribe to my weekly newsletter: bit.ly/laravel-...

Пікірлер: 39

  • @MrEvers
    @MrEvers2 жыл бұрын

    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...

  • @CJMAXiK
    @CJMAXiK2 жыл бұрын

    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.

  • @wildfireDZ
    @wildfireDZ2 жыл бұрын

    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

  • @pauloclara4764
    @pauloclara47642 жыл бұрын

    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...

  • @Recoil13
    @Recoil132 жыл бұрын

    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!

  • @krotetote
    @krotetote2 жыл бұрын

    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.

  • @tesshsu1
    @tesshsu12 жыл бұрын

    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

  • @mohammadashrafuddinferdous8649
    @mohammadashrafuddinferdous86492 жыл бұрын

    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.

  • @osawereao
    @osawereao7 күн бұрын

    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.

  • @vzlamrbeastfan
    @vzlamrbeastfan2 жыл бұрын

    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

  • @Jurigag
    @Jurigag2 жыл бұрын

    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).

  • @BelgranoK
    @BelgranoK2 жыл бұрын

    Great video! I prefer to code constants in the related models o services. If required by a change of functionality I move to database.

  • @DanielDW69
    @DanielDW692 жыл бұрын

    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.

  • @tetleyk
    @tetleyk2 жыл бұрын

    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.

  • @GergelyCsermely
    @GergelyCsermely2 жыл бұрын

    If the code-table is more or less fixed then it is excellent solution.

  • @himak21
    @himak21 Жыл бұрын

    Best KZreadr for me ❤

  • @alexaverkiyev9099
    @alexaverkiyev90992 жыл бұрын

    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).

  • @MonethiTebohoArthurnacious
    @MonethiTebohoArthurnacious2 жыл бұрын

    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 😉

  • @ryanb509
    @ryanb5092 жыл бұрын

    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.

  • @pwcodigo
    @pwcodigo Жыл бұрын

    Obrigado pelo conteúdo !

  • @SaiyanJin85
    @SaiyanJin852 жыл бұрын

    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

  • @leonardoldr

    @leonardoldr

    2 жыл бұрын

    Totally agree. Constants should be used, in it's nature, to better readability and as the name says, constant values.

  • @KamranBhutto
    @KamranBhutto2 жыл бұрын

    Thanks a lot for the video

  • @tinmancode
    @tinmancode2 жыл бұрын

    database all day everyday 24/7 it is dynamic and modifications are mostly straight forward

  • @vladnicu3655
    @vladnicu36552 жыл бұрын

    Please make a new video on how you use the foreign keys logic

  • @JohnToridas
    @JohnToridas2 жыл бұрын

    i usually store constants in a seperate config file. and then access them with Config::get(const_name )

  • @abdulkhan9967
    @abdulkhan9967 Жыл бұрын

    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]

  • @pauloclara4764
    @pauloclara47642 жыл бұрын

    would it be possible to make a video about fullcalendar mainly about drop events from a list from the database to the calendar...thanks

  • @denisgillier4071
    @denisgillier40712 жыл бұрын

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

  • @HawrazNawzad93
    @HawrazNawzad932 жыл бұрын

    how can use unique validation for 3 column like (firstname , middlename , lastname )

  • @LaravelDaily

    @LaravelDaily

    2 жыл бұрын

    Custom validation rule

  • @arianaromero9552
    @arianaromero95522 жыл бұрын

    me too, I prefered to use DB for const, status, tickets etc.

  • @yosuajuliando
    @yosuajuliando2 жыл бұрын

    implementation of the Apriori algorithm in laravel, can you give an example of this?

  • @LaravelDaily

    @LaravelDaily

    2 жыл бұрын

    Never done it myself

  • @yosuajuliando

    @yosuajuliando

    2 жыл бұрын

    @@LaravelDaily as a newbie in laravel, i'm confused😶

  • @demiurgich
    @demiurgich2 жыл бұрын

    Database is my choice.

  • @marcin2828t
    @marcin2828t2 жыл бұрын

    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.