Back to Course |
Laravel 11 Eloquent: Expert Level

Model casts(): Dates, Enum and More

In your Eloquent Models, you can provide casts to automatically cast database columns to some type that you would need to use separately with that type of logic. Probably the most popular example is about date type.


In the User Model, by default, the email_verified_at is cast to datetime.

class User extends Authenticatable
{
// ...
 
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

What does this cast mean? It means that it will be automatically cast to a Carbon object, which means you can use the Carbon function directly on this field.

For example, using Tinker, we have a user, and we can use the diffForHumans() Carbon function directly on the email_verified_at column.

In Laravel 10 and older versions, the casting is provided in the $casts array property instead of a method.

class User extends Authenticatable
{
// ...
 
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

In Laravel 11, you can use either a method or a property, with method having higher importance.


Another example is if you use PHP Enum classes, you must cast the database column to that Enum.

For example, an Enum class with some levels in DB would be stored as an integer.

enum UserLevel: int
{
case Junior = 1;
case Mid = 2;
case Senior = 3;
}

In the User Model, the field is casted to that enum class.

use App\Enums\UserLevel;
 
class User extends Authenticatable
{
// ...
 
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'user_level' => UserLevel::class,
];
}
}

Again, we have a user in the Tinker where the user_level is an integer.

But because it is casted to the Enum class, we can use name or value on that field.