PttRulez
PttRulez

Reputation: 165

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

Upvotes: 2

Views: 1211

Answers (1)

lagbox
lagbox

Reputation: 50491

$changes is a variable that the Model already defines, which is where it keeps the changes to the attributes to know if the model is dirty. This is protected. When you are outside the model it is not an accessible property so __get is called which will call getAttribute. When you are inside the model $changes is accessible so you get the actual property named changes, which is an empty array [] at that moment.

Upvotes: 4

Related Questions