Custom Casts

What are Custom Casts?

Custom Casts in Laravel allow you to define how model attributes are stored in and retrieved from the database. This is useful for transforming data into custom formats or data types, ensuring attributes behave consistently across your application.


Origin

Custom attribute casting was introduced in Laravel to extend the built-in casting functionality, allowing developers to handle more complex transformations.


Why are they important?

  1. Encapsulates Attribute Logic: Keeps attribute transformation logic within the model.
  2. Improves Code Reusability: Custom casts can be reused across multiple models.
  3. Ensures Consistency: Guarantees attributes are always transformed the same way.

Best Practices

  1. Use Casts for Repeated Logic: Encapsulate frequent transformations.
  2. Test Custom Casts: Write tests to validate cast behavior.
  3. Keep Casts Focused: Each cast should handle a single type of transformation.

Example in Action

Create a custom cast:

php artisan make:cast JsonToCollection

In the generated class:

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Collection;

class JsonToCollection implements CastsAttributes
{
    public function get($model, $key, $value, $attributes)
    {
        return collect(json_decode($value, true));
    }

    public function set($model, $key, $value, $attributes)
    {
        return json_encode($value);
    }
}

Apply the cast in your model:

protected $casts = [
    'settings' => JsonToCollection::class,
];

Now, the settings attribute will automatically transform between a JSON string in the database and a Laravel collection in your application.