How to Use Casts in Eloquent Models in Laravel
In Laravel Eloquent, use the
$casts property in your model to automatically convert attributes to common data types like integer, boolean, array, or datetime. Define $casts as an array where keys are attribute names and values are the desired types, so Eloquent handles conversion when you get or set those attributes.Syntax
The $casts property is an array in your Eloquent model where each key is the attribute name and the value is the type you want to cast it to. Common types include integer, boolean, array, json, datetime, and float.
This tells Eloquent to automatically convert the attribute to that type when you access or set it.
php
class User extends Model { protected $casts = [ 'is_admin' => 'boolean', 'options' => 'array', 'created_at' => 'datetime', 'score' => 'float' ]; }
Example
This example shows a User model with casts for is_admin as boolean, preferences as array, and created_at as datetime. When you access these attributes, they are automatically converted to the correct types.
php
<?php use Illuminate\Database\Eloquent\Model; class User extends Model { protected $casts = [ 'is_admin' => 'boolean', 'preferences' => 'array', 'created_at' => 'datetime' ]; } // Usage example $user = new User(); $user->is_admin = 1; $user->preferences = ['theme' => 'dark', 'notifications' => true]; $user->created_at = '2024-06-01 12:00:00'; // Accessing attributes var_dump($user->is_admin); // bool(true) var_dump($user->preferences); // array with keys 'theme' and 'notifications' var_dump($user->created_at->format('Y-m-d')); // string '2024-06-01'
Output
bool(true)
array(2) {
["theme"]=>
string(4) "dark"
["notifications"]=>
bool(true)
}
string(10) "2024-06-01"
Common Pitfalls
- Not defining casts for attributes that need type conversion can cause unexpected data types.
- Using
arrayorjsoncasts requires the attribute to be stored as JSON in the database. - Trying to cast attributes that do not exist or are not fillable will have no effect.
- Setting a cast to
datetimeexpects the attribute to be a valid date string or timestamp.
Always ensure your database columns match the expected data format for the cast.
php
class Product extends Model { // Wrong: casting 'tags' as array but stored as plain string protected $casts = [ 'tags' => 'array' ]; } // Correct: store 'tags' as JSON in DB for array cast to work // Also ensure 'tags' column type is JSON or TEXT with JSON content
Quick Reference
| Cast Type | Description |
|---|---|
| integer | Converts attribute to integer |
| boolean | Converts attribute to true or false |
| float | Converts attribute to float number |
| string | Converts attribute to string |
| array | Converts JSON attribute to PHP array |
| json | Converts attribute to JSON string |
| datetime | Converts attribute to Carbon date object |
| date | Converts attribute to date without time |
| collection | Converts attribute to Laravel Collection |
Key Takeaways
Use the $casts property in your Eloquent model to define attribute type conversions.
Common cast types include boolean, integer, array, datetime, and float.
Ensure your database columns store data in compatible formats for the casts to work correctly.
Casts automatically convert attributes when you get or set them, simplifying data handling.
Avoid casting attributes that do not exist or are not properly stored in the database.