How to Define Casts in a Query in Laravel using withCasts()

How to Define Casts in a Query in Laravel using withCasts()

Laravel allows you to define casts at query time that means you can use withCasts() method to define a cast at query time. Today we will learn how to define casts in a query with the help of withCasts() method.  Casting allows you to convert the data types of specific model attributes when retrieving or setting them.

 

 

Let's see some example how we define casts at query time:

 

 

Example 1: Convert double into integer

 

Suppose you have a table and it has a column price which data type is double and you want to change the type into integer while retrieving data from database.

<?php 

$products= Product::select(['name','color','price'])
->withCasts(['price' => 'integer'])
->get();

 

The above query gives you the integer value for the price column.

 

 

 

Example 2: Convert date into string

 

Think you have a column expire_date which type is timestamp and now convert it string using the below casting at query time.

<?php 

$subscriptions= Sbscription::select(['expire_date'])
->withCasts(['expire_date' => 'string'])
->get();

 

Now the above query gives you the string value for the expire_date column.

 

 

 

If you like what you are reading, please think about buying us a coffee as a token of appreciation.

Buy Me A Coffee

We appreciate your support and are committed to providing you useful and informative content.

We are thankful for your ongoing support 

Tags

  • Share This: