PHP 8.1: Enums - Everything You Need To Know | How to use enumerations in Laravel?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] thank you hello developers Welcome to our Channel my name is Harish Kumar in PHP 8.1 we have a new feature that is enumerations and enumeration or an enum per shot is an enumerated type that has a fixed number of possible values for example let's say we have a post class and it has a property status and its possible values are draft in review or published so here we use enum which means specifically listed values so in this video we will see what is PHP enum in PHP version 8.1 and how we can use it in the laravel application so before moving ahead if you are new to this Channel please hit the red subscribe button and press Bell icon so when I upload new videos you get notified for this tutorial I have already prepared a laravel application and in this application I have already created a post model and here is the post controller in this index method we have displayed a list of posts and create method is for to display a form to create a new post and in this store method we have stored the new Post in the database and in the browser you can see here we have list of posts here we have post titles and you can also see that the post has status property as well which has possible values published draft and in a review so how we used to handle this before PHP enum feature let's see some developers use to create constants in the model class for example in the post model here let's create a constant variable public const draft status is equal to draft and similarly published status is equal to published it is not bad but I think it is better to create dedicated class for these constants so let's remove this and I have already prepared a post status class this one and here I have defined all the constants related to post status property and we use these constants throughout the code for example if you want to use those you could do something like this in the post controller left item is here post status colon colon draft and make sure to import this class this one and now if you go to browser and refresh it will give us the string value of this constant this is not a bad approach it is certainly better than hard coding such values that don't really change and remain static this is good enough but this does not really help well with the type hinting let's see what I mean so in the post controller let's remove this and here in this index method here I am using four service class and this post service class has a static Method All to fetch all posts let's see this so here is the post service class and here we have static method all and it simply returns all the latest ports so let's say here we want to fetch only published pause so what here we will do first here in this all static method here I'll pass post status published now let's go to this method and here it is going to accept dollar status so here if I die dump this status and let's go to browser refresh and you will see that we get published stream so here we will type in this as a string because we know that the type of the status is a string and next here we will say where status is dollar status now let's remove this and go to browser refresh and here we get all the published posts now the problem with this constant is that we are only able to type in the type of scalar value that is a string in this case because the post status constants we have these are the strings if these were the integer values then we would type in this as end so the problem is that it does not really guarantee that the provided value is one of these constants from the post status it could be any string for example here if I pass any random string this would still work so if we refresh the page of course we are not going to get any post but our code still works we are able to pass any other string because of this we usually add some additional logic to ensure that the passed in value is really a valid constant value if not we might throw an exception let's see how it looks so first in the post status class here I will add a static method let's say it is public static function all and it will return an array of these possible values or you can say all these constants so here I'll say return an array and then here I'll say sell draft in review and published next in the post service class here I will add a if condition if in Array and here I'll pass dollar status and next post status all so if this status is not in this post status all then here we will throw an exception so throw new exception let's say exception message is invalid status value now in the browser if I refresh and here we get exception invalid status value because in the post controller here we have passed random string which is not in the poster consents so now if I pass post status in review now it should work let's see refresh and here we go we get the all post which has status in review well this is not bad and actually good approach and better approach than hard coding things around but this additional logic would occur in multiple places where these constants are accepted the another problem is that in the browser here the status label is in underscore review here you may not want to display the text like this and you may want to display something else instead of this text for better example let's say in the post status class here these constant values are string but sometime developers choose integer value instead of strings for example let's say this draft is a 0 and in review is a 1 and published is a two now let's regenerate the post data so in the terminal PHP Artisan my create fresh and also save the data it's done now in the browser refresh this time you will see it has displayed the number for the status instead of proper text so here again you need additional logic to display proper text so for these kind of problems enum comes to rescue which provides a better handling for this now let's try the new enum feature enums are kind of regular class so to create enumclass here instead of this class we use enum keyword like this enumclass can have constant variables so these variables are valid but for fixed set of possible values we can define something called cases instead of using constants this way so let's comment all of these for now and now let's define cases so the syntax goes like this case followed by the name of case that is draft in our case and then semicolon similarly in review and published as you may have noticed these cases by default have no scalar values like we have for these constants we will talk about the scalar values in a few moments here each case is an object of enum class itself so in this case these cases are basically object of the post status in a class to verify this let's go to the Post controller here my data is showing me error so for now let's comment this and let's write down post status colon colon draft and now let's go to browser refresh and here you can see it is an object of post status and it has a property name which is the name of the case that is draft in this case so this kind of case which does not have scalar value is called Pure case and the enum class which has pure cases is called Pure enum so right now this post status is a pure enum we can assign some values to these cases the same way we have assigned values to these constants so we could do case trapped is equal to zero in a review is equal to 1 and published is equal to 2. now this case becomes a backed case and an innum class with all bagged cases is called bagged enum now you can also notice that the editor is showing error for these cases that is because it is important to actually make this enum we are backed enum we need to type hint this enum class with the data type of the scalar value of this case in this case we are using integer we need to type print this as int like this so now our enumclass has backed cases so the post status in a class is backed enum and remember that in a Class Type can only be integer or string we cannot type Hint it as an array or object or any other class it can only int or string we can also cannot type hint as Union type so we cannot do int or say or something like that it has to be either end or string if I type it it as string now my editor showing me an error in a case type int does not match in a backing type string so I will revert back to it because the enumclass can only either be integer or sing so we cannot have a mix of backed and pure cases for example if I remove value of this draft this is not going to work case draft or backed enum post status must have a value so this means that either all cases have to be backed or all of them to be pure and also the value of for these cases must be unique so if two cases have the same value it will throw an error so here if I say in a review is equal to 0 now you can notice editor is showing error message duplicate value in enum for case draft and in review so we have to have unique values now how do we actually access these values so let's go to the Post controller here we have already died up the post status draft so let's go to browser and refresh this time you can see we have two properties for this object one is name which is the name of the case and second is the value which is the scalar value of the backed case so for Pure case we have only one property that is name and for bagged case we have two properties that is name and value so here to get its value we can say value like this now I go to browser refresh here we get the value 0 so if I type here post status in review and then its value now let's see its value in the browser refresh it is one now let's fix this implementation so uncomment this and you can see it is showing an error because this all method accepts status as string but we have seen in this DD this post status in review is an object because we are working with objects instead of scalar value constants we can actually add post status type painting where these enum cases are accepted which is one of the main benefits of using enums so in the post status here instead of type painting it as a string we can actually type it as post status like this now we do not need this condition because we are now type painting so we know for sure that the passed in value is an object of post status so we know it is a valid status so we can get rid of this now let's go to the browser refresh we get one because I forgot to remove the die dump from the controller let's remove this and now go back to browser refresh and here the error gone and we have passed the in review ports now let's go to the editor and now if I die dump this status and refresh here you can see it is an object because here I am in the laravel application so behind the scene laravel has automatically detected that this status is an enum class so it has automatically get the statuses value but if you are working on a core PHP or any other framework when you are making a database query that time you may get fatal error if you pass an object so you have to pass the scalar value so you can say status and then access the value like this so now in the browser refresh it works now in the statuses you can see it is displaying the integer value which is the row value saved in the database this is not user friendly right for better user experience we would display some user friendly text so in the editor let's open our view file index.blade.php and scroll down right here we have displayed the Raw Status value so to display user friendly text first we need to able to get the post status object from the Raw Status value so if the value is 2 then we want to get the object of published case if the value is 1 then we want the object of in review case and so on so the backed enum provides two methods one is the pro and second is try from both of these method except scalar value as an argument and returns and in a case if found let's see this so in the controller so here plus diagram post status from let's pass the scalar value for draft 0 now let's go to browser and refresh here we get object of post status for case draft similarly if I pass the one which is the value for in review so one let's go to browser and we get in review case similarly from 2 we will get object for published now if I pass any another number which is not present in the post status enum then it will throw an exception let's try 3 which is not present here so let's go to browser refresh and here we get exception 3 is not a valid backing value for enum post status now if I try the second method try from which is also same it accept the scalar value and Returns the enum case if found but it does not give exception and it does not found in the enum class let's see refresh and here we get null because these three scalar value is not present in the post status but if I pass 2 then here refresh and here we get the published status so let's comment this now let's refresh so now in the view first we will try to get the post status object from this raw value so here we can say app enums and then post status and then colon colon here I will use try from because it will not throw an exception if it does not find case in default status and then here I will pass the row value post status it will still not work because it will try to print the object of the found case let's see and here we get the error argument one string must be type of string for status object is given so here we need to call some kind of method something like text or let's say label which will give us the user friendly text to display for the proper case so we will create the label method in the post status class because we no longer need this so let's remove these commenter code and let's create method public function label now from here if I return any string it will print that right here of course we do not want that instead we want to display proper text for these cases so for that first let's Dig Down Dollar Days and if we refresh it will give us the post status which is in review enumclass also allows object comparison so what I mean here if I assign a case to a variable so let's say dollar case 1 is equal to post status draft and case 2 is also post status draft and now let's diagram dollar case one is triple equal to Dollar case to the browser refresh here it is true because both cases are the same but if I say post status in review now in the browser refresh and now it is false because both are different as we have seen the this keyword is an object so here if we will check this is triple equal to post status in review then it will return the in review text for that you can use any condition you prefer you can use if condition or switch for now here I am going to use a new PHP syntax that is match so here I will say return match dollar this if the value is self drop in that case it should return draft if it is in a review then it should return in review and if it is published then it should return published now if you go to browser refresh and now here we get the proper label for the status go to the Post controller and if I pass here post status draft and refresh now we get the draft and if I pass published we will get all the published posts here then you can add another method for example as a color similar like that here we will return this and here we will return the CSS class which will which will display the proper color for draft case because here I am using detail when CSS so here I will return Tailwind CSS class so first let's go to the index blade file and here I am going to copy these two CSS class and and now let's say color code draft is yellow 100 and text color is yellow 800 and similarly for in review here let's say that is red and for published I will say it is green and now in the blade index file here you will say and let's copy this and print it here and now instead of label here we will call method color now let's go to browser refresh and now you can see it is in the green color similarly in the post controller let's get the draft force and refresh now we have draft in yellow colors and let's fetch the in review refresh this is in the red color because I am working in the laravel application and laravel provides casting for enums out of the box so we do not have to get the case object using drive from method like we have implemented right here so instead in the post model here we can say is equal to status is equal to array and it has status which is going to cast in The Host status like this now in the index blade file we do not have to use Stripe from method instead we can say o status level like this similarly similarly for the color we can remove this and we can call post status color and refresh and we get the same result to prove this this is an object let's write down post status and in the browser you can see it is object of post status now let's remove this refresh and everything is working because in the post model we have added a casting for the post status so if we try to create a new post using laravel eloquent feature with any random value of status it will throw an error let's say this so in the post controller let's remove this so let's say post create and then let's pass an array and it has title is equal to test and status is any random value let's say 23 which is not present in the post status cases so now let's go to browser refresh and here we get error 23 is not a valid backing value for enum or status now let's pass one which is interview case now let's go back to browser refresh and this time it has created a test pose which has status in review enumclass also provide one more useful method that is cases which returns all the cases object let's see this as well so so let's dive down post status cases in the browser refresh and we get array of three objects one is the draft second is the interview and third one is the published so where we can use this feature let's remove this so let's say in the create post right now we have only one input Field title for this simple example now let's say in this form you also want to display a drop down for status to save the status of the post as well so let's implement this so in the post create.blade.php here we have input field for title let's duplicate this and here I am going to add class margin top 4 and here it is status and we do not need input field so let's Commit This and here I'll add select it has ID status and class is equal to Let's copy this one next here it is status and the name is also status and to display validation error here we will pass status next here we will say options how we can add all the options for these cases for that we will use in a method cases so here I'll add for each Loop and here I'll say app in um for status cases and as status and then this option tag right here and now here we will display dollar status label and its value is dollar status value like this now let's go to browser undefined constant cases okay mistake is right here it is not a constant it is a method cases refresh and here we have drop down how cool is that and the post controller here we can all add another value request status now let's create a new post post one and select in review submit and here we have post one in review create a post now let's suppose from the inspect element if I change the value of in review to something else let's say 33 which is not a a case in the post status enum now this time if I select in review and and now if I submit we should get an error 33 is not valid backing value for enum so how we can avoid this error we can fix this error by adding validation before creating this post so in the store post request here we will add a validation for status so here we can say status is equal to first thing it is required and then we can say new enum and then we will pass enumclass post that is post status class and make sure to import this enum right here this one so now in the browser let's refresh and right here let's say go to inspect tool and now change its value to 33 let's plot this and select interview and Save it now you can see that we get the validation message the selected status is invalid now the request only accepts enum's backed values enough behave similar to classes when they are used with the functions that supports inspecting classes and objects for example data type is a is object and get class methods these functions behave the same for enums the same as it behaves for the regular class I think I have covered all the features of the enums now let's see what is the difference between the regular class and enums very first difference is the obviously syntax we use class and then the class name foreign keyword and the name of the enum second in the classes we can define properties but enums we cannot define properties what I mean in the class you can Define class and then class name and then it can has property public string test which is valid for regular classes but invalid for enums that is not allowed in the enums we can create methods and static methods that like regular classes and we can initialize classes like new class name but we cannot initialize enums like this regular classes and enums both can have interfaces and a class has a inheritance feature but enum does not have so we can extend regular classes but we cannot extend enum both supports trade but the trades for enum cannot have properties for example let's say this post status uses example trade so use example trade now let's create this trade example trade.php create example trade this is valid we can add as many methods and static methods as you want it will work but we cannot define properties like public strain dollar test this is not allowed in the trade which is used by the enumclass so now let's go to browser and let's go to Ports now you can see that enum post status may not include properties that is defined in this trade right here so if I remove this and refresh it will work it is valid in the enums some of the magic methods are not allowed for example in the enums we cannot use get set construct destruct clone sleep magic methods some of the magic concepts are allowed like we can use colon colon class underscore class function and Method these one this is all in this lesson I hope it was useful and you have enjoyed it thanks for watching if you like the video hit the like button share this video and don't forget to subscribe us see you in the next lesson foreign [Music]
Info
Channel: QiroLab
Views: 3,797
Rating: undefined out of 5
Keywords: qirolab, php8 tutorial, php course, learn php the right way, object oriented php, full php course, php in 2021, advanced php course, php 8.1, enums in php, php 8.1 enum, php enum, enum vs const in php, laravel for beginner, laravel tutorial for beginners, laravel 8 tutorial, laravel 8, laravel advanced tutorial, laravel 8 advanced tutorial, php, php tips, php tips and tricks, laravel, laravel tips
Id: 81b-0E-_EaI
Channel Id: undefined
Length: 38min 28sec (2308 seconds)
Published: Wed Sep 21 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.