Answer the question
In order to leave comments, you need to log in
Lazy loading resource in Laravel if model method doesn't return relation?
Laravel has a nice $this->whenLoaded function for ApiResource for lazy loading of model relationships https://laravel.com/docs/8.x/eloquent-resources#co... .
I have such a problem that I have a property on the model that does not return a relation, but goes to another table in the database, collects apartments according to a certain condition and adds it all to an array (PhpMyAdmin designer below)
In this case, I have addresses and the apartments in them are stored by users in a separate field (well, so as not to produce a lot of addresses, our team leader said that it’s right to do this and we do it, I’m Toko Junior and I’m still learning ¯\_(ツ)_/¯ )
The code for renting apartments is working and looks like this
Address.php
public function apartments() {
return $this->clients->map(function ($item) {
return $item->apartment;
})->sort()->flatten();
}
class Address extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
"id" => $this->id,
"city" => $this->ctiy,
"street" => $this->address,
"house" => $this->house,
$this->corpus ?? "corpus" => $this->corpus,
?? вот эта строчка нужно чтобы была ленивой, но я не могу придумать логику --> "apartments" => $this->apartments()
];
}
}
Answer the question
In order to leave comments, you need to log in
apartments()
describe through hasManyThrough . If the standard features are hasManyThrough
not enough, you can use the eloquent-has-many-deep package .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question