Custom Casts in Laravel

What are Custom Casts in Laravel?

You can specify how Laravel stores and retrieves model attributes from the database using Custom Casts. This is handy for converting data to custom formats or types. It ensures attributes function with reliability throughout your app.


Origin

Laravel added custom attribute casting to extend its built-in casting. This lets developers handle more complex conversions.


Why are Custom Casts Used?

  1. Encapsulates Attribute Logic: Stores attribute transformation logic within the model.
  2. Improves Code Reusability: Custom casts can be applied to many models.
  3. Provides Consistency: Ensures that attributes are always changed in the same way.

Best Practices.

  1. Use Casts for Repeated Logic: Encapsulate common transformations.
  2. Test Custom Casts: Create tests to check the cast behavior.
  3. Keep Casts Focused: Each cast should only handle one 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.

Read more