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.
Laravel added custom attribute casting to extend its built-in casting. This lets developers handle more complex conversions.
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.