Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brian Kidd's avatar

API Resource - access additional attributes

I'm using staudenmeir/laravel-adjacency-list and need to include the depth value in my API response. When I try to access depth within my API Resource, the value, although present in the collection passed to ::make, doesn't seem to be available with $this in the API resource - the call is delegated to the underlying Eloquent model and that's a value added by the package and not present on the database.

Is there a way to access these additional attributes within an API resource?

"descendants" => array:6 [▼
    0 => array:11 [▶]
    1 => array:11 [▼
      "id" => 39
      "name" => "Office Computations & Mobilization"
      "abbreviation" => null
      "budget_by_option_id" => null
      "parent_id" => 38
      "team_id" => 1
      "created_at" => "2023-01-30T21:01:01.000000Z"
      "updated_at" => "2023-01-30T21:05:15.000000Z"
      "depth" => 2
      "path" => "38.39"
      "budget_items" => array:2 [▼
        0 => array:16 [▶]
        1 => array:16 [▶]
      ]
    ]
0 likes
3 replies
azimidev's avatar

Yes, you can access these additional attributes in your API resource by using the $appends property on your Eloquent model. The $appends property is an array of attribute names that should be included in the model's array and JSON representation.

class YourModel extends Model
{
    protected $appends = ['depth'];

    public function getDepthAttribute()
    {
        return $this->attributes['depth'];
    }
}

Then in your API resource, you can access the depth attribute as if it was a property of the model:

class YourResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'depth' => $this->depth,
            // ...
        ];
    }
}

Then you can access it directly in your API resource using $this->depth.

1 like
azimidev's avatar

@Brian Kidd if I answered you correctly please choose it as the best answer. thank you

Please or to participate in this conversation.