DEV Community

loading...
Cover image for Type casting in Laravel

Type casting in Laravel

ajayyadav profile image Ajay Yadav ・2 min read

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 Boolean.
Simply put, type casting is a method of changing an entity from one data type to another.

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 integer, real, float 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',
]
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (2)

pic
Editor guide
Collapse
fiveko profile image
fiveko

Nice article. As a side note, you may correct "'status' => 'boolena'," to "boolean".

Collapse
ajayyadav profile image
Ajay Yadav Author

🤔😜 Yup typo 🙏🙏 thank you