Throttlehead
Throttlehead

Reputation: 1945

Laravel model attribute is null in the json response

Using Laravel 4.2 here. I have a model with a 'status' attribute. I declared an accessor like so:

public function getStatusAttribute($status) {
  if (isset($this->expires_at) && strtotime(\Carbon\Carbon::now()) > strtotime($this->expires_at)) {
    return 'expired';
  }

  return $status;
}

As you can see, I'm attempting to overwrite what is passed in from the database by checking for an expiration date. This all appears to work fine accept when the model is sent back as JSON from my api. The model's status ends up being null.

The attribute is in both the visible and appends array, and when i var dump it like this in the REST controller, the status is correct:

var_dump($item->status);

This returns the correct status. Anyone know what might be going on behind the scenes in Laravel? Is this a bug?

Upvotes: 0

Views: 2030

Answers (1)

Throttlehead
Throttlehead

Reputation: 1945

Well it seems the fix was to remove 'status' from the model's appends array. It seems like things have been being changed with the way the visible and appends arrays are used during json/array casting over the course of Laravel 4's updates.

Sometimes I need to have them in both for my attributes to work correctly, or sometimes just in the 'visible'. It's very strange and I'm wondering if these things have been clarified further in Laravel 5. Maybe I'll take a look at the source code to see if I can figure out how these arrays are extended/mapped.

I'll leave this here for anyone who runs into a similar problem.

Upvotes: 1

Related Questions