← Back to all snippets
PHP

Cast Database Columns to Specific PHP Types

Automate type conversion for database columns in Laravel Eloquent models by casting attributes to arrays, JSON, booleans, or datetimes for efficient handling.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $casts = [
        'options' => 'array', // Casts a JSON string column to a PHP array
        'is_published' => 'boolean', // Casts an integer (0/1) to a boolean
        'release_date' => 'datetime:Y-m-d', // Casts to a Carbon instance, formatted on output
        'settings' => 'json', // Casts a JSON string to an associative array/object
        'price' => 'decimal:2', // Casts a numeric value to a float with 2 decimal places
    ];
}

// Usage example:
$product = Product::find(1);
if ($product->is_published) { /* ... */ }
$options = $product->options; // $options is now a PHP array
$settings = $product->settings; // $settings is now a PHP array/object
$releaseDate = $product->release_date; // $releaseDate is a Carbon instance
$formattedDate = $releaseDate->format('F j, Y');
How it works: Eloquent's `$casts` property provides a convenient way to automatically convert attribute values to common PHP data types when they are retrieved from the database and back when they are saved. This eliminates the need for manual type juggling, ensuring data consistency and simplifying interaction with database columns that store serialized data (like JSON) or boolean flags, directly integrating with Carbon for dates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs