What Is Query Time Casting In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column.

What Is Query Time Casting In Laravel With Example

Query Time Casting

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\Post;
use App\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();


To learn more about Attribute Casting in laravel visit out Bajarangisoft site

Related Post