PHP

Type Conversion with Laravel Eloquent Attribute Casting

Automatically convert database attributes to specific PHP data types like arrays, collections, booleans, or custom casts when retrieving them.

// In App\Models\Product.php
class Product extends Model
{
    protected $casts = [
        'is_featured' => 'boolean',
        'options' => 'array',
        'price' => 'float',
        'published_at' => 'datetime',
    ];
}

// Usage:
$product = App\Models\Product::find(1);

if ($product->is_featured) { // is_featured is automatically a boolean
    echo "This product is featured.
";
}

// options is automatically an array
foreach ($product->options as $option) {
    echo "Option: " . $option . "
";
}

echo "Price: " . gettype($product->price) . " -> " . $product->price . "
"; // float
echo "Published At Type: " . get_class($product->published_at) . "
"; // Carbon instance
How it works: Attribute casting in Eloquent allows you to automatically convert the data types of your model attributes when they are retrieved from or saved to the database. This is extremely useful for handling common data types like booleans, integers, floats, arrays (for JSON columns), and dates (converted to Carbon instances) without manual conversion. It simplifies data manipulation, ensures type consistency, and reduces boilerplate code within your application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs