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

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
whereBinary(): Case-Sensitive MySQL Queries in Laravel image

whereBinary(): Case-Sensitive MySQL Queries in Laravel

Read article
Compile PHP to Native Binaries with TypePHP image

Compile PHP to Native Binaries with TypePHP

Read article
State of Laravel 2026 Survey Is Now Open image

State of Laravel 2026 Survey Is Now Open

Read article
Testing Best Practices Skill in Laravel Boost v2.6.0 image

Testing Best Practices Skill in Laravel Boost v2.6.0

Read article
Query Binding Masking and whereBinary() in Laravel 13.27 image

Query Binding Masking and whereBinary() in Laravel 13.27

Read article
Laravel AI: Load Tools On Demand With ToolSearch image

Laravel AI: Load Tools On Demand With ToolSearch

Read article