eggplantSword's avatar

selectRaw on relationship for eager loading

I have this code, but I want to return the id and label for all relationships instead of description and name

 return Model::query()->with('product:id,description', 'subCategory:id,name', 'status:id,name')->get();

I can do it this way. I like the top as its really short and condensed. How can I get this code shorter/better?

return Model::query()
            ->with('product', function ($query) {
                $query->selectRaw('id, description as label');
            })
            ->with('subCategory', function ($query) {
                $query->selectRaw('id, name as label');
            })
            ->with('status', function ($query) {
                $query->selectRaw('id, name as label');
            })->get();
0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Just make a label accessor on each of the Product, Status and SubCategory models and the original Eloquent query will still work. Otherwise, your only option is short-closures:

return Model::query()
            ->with('product', fn ($query) => $query->selectRaw('id, description as label'))
            ->with('subCategory', fn ($query) => $query->selectRaw('id, name as label'))
            ->with('status', fn ($query) => $query->selectRaw('id, name as label'))
            ->get();

Please or to participate in this conversation.