News

🔥 Define Casts in a Query

Published
🔥 Define Casts in a Query image

Laravel has Eloquent attribute and custom casting. But did you know about query-time casting? It's documented in Laravel, and illustrated beautifully by Aaron Francis:

Given the following query in the Laravel documentation:

use App\Models\Post;
use App\Models\User;
 
$users = User::select([
'users.*',
'last_posted_at' => Post::selectRaw('MAX(created_at)')
->whereColumn('user_id', 'users.id')
])->get();

You can use the withCasts() method to define a cast at query time, giving you the power of complex SQL queries yet still using casts:

$users = User::select([
'users.*',
'last_posted_at' => Post::selectRaw('MAX(created_at)')
->whereColumn('user_id', 'users.id')
])->withCasts([
'last_posted_at' => 'datetime'
])->get();
 
$user->last_posted_at; // DateTime

If you'd like to learn more about casts, check out Eloquent Attribute Casting and Eloquent Custom Casts. I would also recommend checking out Aaron's MySQL for Developers course.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Major performance improvements & security patches for Filament v4.12 and v5.7! image

Major performance improvements & security patches for Filament v4.12 and v5.7!

Read article
Laravel Boost Project Rules: Teach Agents Your Conventions image

Laravel Boost Project Rules: Teach Agents Your Conventions

Read article
Extract an Image's Dominant Color in Laravel image

Extract an Image's Dominant Color in Laravel

Read article
Image Dominant Color and HEIC Support in Laravel 13.24 image

Image Dominant Color and HEIC Support in Laravel 13.24

Read article
Official Laravel Zed Extension: LSP for PHP & Blade image

Official Laravel Zed Extension: LSP for PHP & Blade

Read article
Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD image

Laravel Head: Manage Meta Tags, Open Graph, and JSON-LD

Read article