Answer the question
In order to leave comments, you need to log in
Why is the custom attribute not loading?
There is a Clinic with many Doctors. The Doctor has a custom property "custom_atr" that I want to add to the output (I know what can be written in the model class protected $appends = ['custom_atr'];
, but this will always be distributed.)
Here is the code.
$clinic = $clinic->find(1);
$clinic->load([
'doctors' => function ($q) {
$q->each(function ($doctor) {
$doctor->append('custom_atr');
});
}
]);
Answer the question
In order to leave comments, you need to log in
The closure passed to the "load" method of the model or to the "with" method of the query builder takes as input Illuminate\Database\Eloquent\Relations\Relation (in this case, maybe HasMany or BelongsToMany). That is, it is the same as if you wrote:
$clinic->doctors()->each(function ($doctor) {
$doctor->append('custom_atr');
})
$clinic = Clinic::with('doctors')->find(1);
$clinic->doctors->each(function ($doctor) {
$doctor->append('custom_atr');
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question