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.
Test what you just learned with 31 interactive multiple-choice questions and instant explanations.
- Nazmul Hoque
- Jun 21, 2023
- 2 min read
- 4003
Tags
Share This:
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.

