Laravel

Using the withCasts method for dynamic attribute casting 💡

Laravel's Eloquent ORM allows you to cast attributes to native types, but sometimes you might want to apply casts dynamically based on certain conditions. The withCasts method allows you to do just that.

use App\Models\User;

$user = User::query()
    ->withCasts([
        'is_active' => 'boolean',
        'last_login_at' => 'datetime',
        'metadata' => 'array'
    ])
    ->find(1);

// Now $user->is_active is a boolean
// $user->last_login_at is a Carbon instance
// $user->metadata is an array