My Model
class Subscriber extends Model
{
protected $casts = [
'filters' => 'object'
];
}
In tinker:
$s = App\Subscriber::first();
$s->filters
// prints serialized json:
// ""{\"maxHyra\":\"8000\",\"minAntalRum\":\"2\",\"Ungdom\":\"true\",\"Student\":\"true\",\"Korttid\":\"true\",\"Bostadssnabben\":\"true\",\"_token\":\"0Y2f3eAl27ikrujvw7VBWNOaNXxchygaFUDSo4s4\"}""
json_decode($s->filters)
// prints a neat php object.
So obviously my data in the attribute is fine, and json_decode works. But the cast is not working. I have also tried accessors without success.
$casts
works both ways, inserting and retriveving. There's no need to use json_encode
to convert a array to string by yourself first. Laravel will do when it is in the $casts
array.
for example:
Model Sample:
protected $casts = ['ext' => 'object'];
SampleController:
App\Sample::create([
'ext'=>['hello'=>'world']
])
Casts works both ways, that is both for insert and retrieving! I had kept json_encode when inserting new Models.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With