Type Casting in Laravel

Casting a value means changing it to (or ensuring it is already) a particular type. Some types you might be familiar with are Integer or BooleanSimply put, type casting is a method of changing an entity from one data type to another.


Type Casting in Laravel

Why should I care about type casting :

So, When you store numbers in database - they are returned as string by default. But type casting allows you to cast them as integerrealfloat or Boolean you can convert 1 and 0 in your database to true and false

Let's do it ...

So in your model you can write :

 
 protected $casts =  [
    'status' => 'boolena',
 ]


It'll convert status(1,0) to true or false. so when you fetch any data from table it'll convert status column to true or false. you don't need to write any logic like this ...

 
if($post->status == "1"){
   // show status active 
 }else{
   // show status inactive
 }



Array & JSON Casting:


Additionally, if your table consist a column which stores serialized JSON string and you want that particular column to be automatically deserialize the attribute to a PHP array when you access it on your Eloquent model, you should use array cast. You can do it like this.

Alt Text

So, you can store JSON tags data into post table , but while fetching the posts you can convert it automatically into PHP array so now you can avoid creating tags table.


Conclusion:

As you can see, Eloquent attribute casting has a ton of potential to free us up from unnecessary repetitive logic, and also sneakily makes it a lot easier to store data in JSON in our database. Good Stuff!
Previous Post
Next Post

Hello, I am Ashish Yadav. Youtuber | Blogger | Programmer | Digital Marketer. Working on 3 Youtube Channel: 1. Expo Ashish 2. Expo Facts 3. Best Code Creator

Related Posts

Do Subscribe My Youtube Channel