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?
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.