🔥 Define Casts in a Query
Published on by Paul Redmond
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:
So I heard y'all like types in your ORM.
— Aaron Francis (@aarondfrancis) June 6, 2023
Laravel allows you to define casts at the model level to handle casting values to their native types.
More interestingly, it also allows you to define them at query time, so you're not sacrificing the power of SQL 💅 pic.twitter.com/rTwT3OmZGJ
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.