Query Casting in Laravel
Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query:
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();
The last_posted_at
attribute on the results of this query will be a raw string. It would be convenient if we could apply a date
cast to this attribute when executing the query. To accomplish this, we may use the withCasts
method:
$users = User::select([
'users.*',
'last_posted_at' => Post::selectRaw('MAX(created_at)')->whereColumn('user_id', 'users.id')])->withCasts([
'last_posted_at' => 'datetime'])
->get();