Search
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 

🎯 Interactive Skill Assessment
Laravel Challenge: How Well Do You Know the PHP Framework Devs Love?

Test what you just learned with 31 interactive multiple-choice questions and instant explanations.

Start Free Quiz

Tags

Share This:

NH
Written by Nazmul Hoque • Senior Full-Stack Developer (8+ Years Experience)

Senior Full-Stack Engineer with 8+ years of experience building production web and mobile applications using Laravel, Next.js, TypeScript, JavaScript, React, Vue.js, MySQL, PostgreSQL, and Flutter.

You May Also Like Below Articles

Handpicked related tutorials and step-by-step developer guides to continue learning.