0
0
LaravelHow-ToBeginner · 3 min read

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 array or json casts 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 datetime expects 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 TypeDescription
integerConverts attribute to integer
booleanConverts attribute to true or false
floatConverts attribute to float number
stringConverts attribute to string
arrayConverts JSON attribute to PHP array
jsonConverts attribute to JSON string
datetimeConverts attribute to Carbon date object
dateConverts attribute to date without time
collectionConverts 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.