@phpMick you can if you add protected $appends = ['accessor_name']; on your model... but yet again you MUST use with to eager load the relationship that you use.
@phpMick I you are just getting 1 item you can use lazy eager loading in the accessor, but be aware that this wont work as expected if you are loading multiple items of the parent
@Nakov I don't think that is correct. Appends will add it to the list of attributes to get serialised but it won't actually load it. I'm using a resource so I specify which fields to include anyway.
public function things(): HasMany
{
//etc
}
public function getComplexThingsAttribute()
{
$collection = $this->things;
//complex iteration with things to make an array
return $array;
}
ThingResource
public function toArray($request): array
{
return [
//other attributes
$this->complexThings, // this needs to be already loaded here
]
}
@phpMick You will either need to do it always using protected $with on the model or call it when needed.
But if the parent model is just 1 (first or find), you can use eager lazy loading
public function getComplexThingsAttribute()
{
$this->loadMissing('things'); //load the relationship if it isnt loaded
$collection = $this->things;
//complex iteration with things to make an array
return $array;
}