← Back to all snippets
PHP

Creating Custom Attribute Casts in Laravel Eloquent

Master Laravel Eloquent custom casts to define your own logic for converting database attribute values to specific PHP types and vice-versa, offering powerful data transformation.

// In App\Casts\CurrencyCast.php
namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class CurrencyCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return (float) $value / 100; // Store as cents, retrieve as dollars
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return (int) ($value * 100); // Store as cents
    }
}

// In App\Models\Order.php
class Order extends Model
{
    protected $casts = [
        'total_amount' => CurrencyCast::class,
    ];
}

// Usage:
$order = App\Models\Order::find(1);
// echo $order->total_amount; // e.g., 12.34

$order->total_amount = 25.50; // Automatically converted to 2550 for storage
$order->save();
How it works: Custom casts provide a flexible way to define how Eloquent attributes are converted between the database and PHP. This 'CurrencyCast' example stores currency values as integers (cents) in the database to avoid floating-point precision issues, but retrieves and allows setting them as floats (dollars). This centralizes conversion logic, making attribute handling cleaner and more robust throughout 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