Customizing Attribute Type Casting in Eloquent Models
Owner: SnippetBot
Created: 2026-11-04 00:00:16
Size: 1.67 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace App\Models;
use App\Casts\JsonSerializableObject;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'options' => 'array', // Casts JSON column to PHP array
'metadata' => 'object', // Casts JSON column to PHP stdClass object
'published_at' => 'datetime', // Casts to Carbon instance
'is_active' => 'boolean', // Casts to boolean
'price' => 'float', // Casts to float
'settings' => JsonSerializableObject::class, // Using a custom cast class
];
// Example of a custom cast class (App\Casts\JsonSerializableObject.php)
/*
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Arr;
class JsonSerializableObject implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return $value ? json_decode($value) : null;
}
public function set($model, string $key, $value, array $attributes)
{
return json_encode($value);
}
}
*/
}
// Usage:
$product = Product::find(1);
$product->options = ['size' => 'M', 'color' => 'blue']; // Automatically converts to JSON on save
$product->save();
$retrievedProduct = Product::find(1);
$optionsArray = $retrievedProduct->options; // Is now a PHP array
$publishedDate = $retrievedProduct->published_at; // Is a Carbon instance
$settingsObject = $retrievedProduct->settings; // Is an object deserialized by custom cast