I am trying to eager load a model in laravel but only return certain columns. I do not want the whole eager loaded table being presented.
public function car
The answers from shahrukh-anwar and Bogdan are both excellent and led me to solving my version of this problem.
However, there's one critical piece i would add for clarification (even the docs don't mention it).
Take the following, which was still broken for me:
Car::with('owner:id,name,email')->get(['year', 'vin']);
You rarely see specific column selection on the primary model (->get(...)) so it's easy to forget: your selection needs the foreign key column:
Car::with('owner:id,name,email')->get(['owner_id', 'year', 'vin']);
Sure, it seems obvious once you make the mental connection between with using a Closure and this syntax, but still, easy to overlook.
When you have tables with 30+ columns and only need 3 of them, this might keep your memory load down a bit.