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.
Custom attribute casting was introduced in Laravel to extend the built-in casting functionality, allowing developers to handle more complex transformations.
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.