Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 casts not working

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.

like image 835
ajthinking Avatar asked Aug 21 '17 14:08

ajthinking


2 Answers

$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']
])
like image 130
Charlie Avatar answered Oct 20 '22 02:10

Charlie


Casts works both ways, that is both for insert and retrieving! I had kept json_encode when inserting new Models.

like image 3
ajthinking Avatar answered Oct 20 '22 02:10

ajthinking