jeudi 19 novembre 2020

Model property casts empty array in Laravel when it shouldn't

everyone. Model has a property

protected $casts = ['changes' => 'array'];

It's saved by laravel in db automatically as json object. For example

{"before":{"title":"Title1"},"after":{"title":"Title2"}}

But when I try to get it in a controller method as $this->changes it returns empty array [] for some reason. I created a getter:

    public function getTestAttribute()
    {
        return $this->changes;
    }

And that's what i get in tinker:

>>> $activity->changes
=> [
     "before" => [
       "creation_date" => "2021-05-12",
     ],
     "after" => [
       "creation_date" => "2020-07-07 00:00:00",
     ],
   ]
>>> $activity->test
=> []

And the same thing happens in a method where I reference the property. Undefined index because it's an empty array

$before = $this->changes['before'];

PHP Notice:  Undefined index: before

I have no idea what's going on and why it's empty



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/374CjiP
via IFTTT

Aucun commentaire:

Enregistrer un commentaire