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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Route::query() and Model defaults() in Laravel 13.35 image

Route::query() and Model defaults() in Laravel 13.35

Read article
Laravel AI SDK 1.1 Adds Agent Skills and Cohere Chat image

Laravel AI SDK 1.1 Adds Agent Skills and Cohere Chat

Read article
VMPal: Give Your AI Agent a Whole Computer image

VMPal: Give Your AI Agent a Whole Computer

Read article
Synapse: A Dev Dashboard for Laravel AI SDK Agents image

Synapse: A Dev Dashboard for Laravel AI SDK Agents

Read article
Decide with Jev: Three Questions in One Request with the Laravel AI SDK image

Decide with Jev: Three Questions in One Request with the Laravel AI SDK

Read article
Grant: Enum-Based Roles and Permissions for Laravel image

Grant: Enum-Based Roles and Permissions for Laravel

Read article