PHP
Automatically Convert Eloquent Model Attributes with Type Casting
Discover how Eloquent attribute casting automatically converts model attributes to common PHP data types like arrays, booleans, dates, or custom types, simplifying data handling.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'is_admin' => 'boolean',
'options' => 'array',
'settings' => 'json',
'birth_date' => 'date',
];
}
// Usage example:
// $user = User::find(1);
// if ($user->is_admin) { ... } // $user->is_admin is a boolean
// $options = $user->options; // $options is a PHP array
// $emailVerified = $user->email_verified_at; // $emailVerified is a Carbon instance
How it works: Eloquent attribute casting provides a convenient way to automatically convert attribute values to common data types when they are accessed or set on a model. By defining the `$casts` property on your model, you can specify how database column values (e.g., JSON strings, integer `0`/`1`) should be converted into PHP types like arrays, booleans, `Carbon` date objects, or even custom cast types. This eliminates the need for manual type conversions in your code, making your models more robust and easier to work with.