Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

armingdev's avatar

Select columns on relationship tables

Hello,

Im looking for good way to make query with eager loader on relationship tables, but to take only columns that i need (select or pluck).

$parts = Parts::with('cars', 'bikes', 'formulas')->get();

This work but it returns too much data from relationship tables. How can I select for example just 2 columns to return data from this cars, bikes, formulas tables. Off course tables have same columns that Im trying to query (id, name).

Thank you

0 likes
8 replies
guc43's avatar

Hey,

try this:

$parts = Parts::with(['cars' => function ($query) {
    $query->get(['column1', 'column2']);
}, 'bikes', 'formulas'])->get();

Cant test it right now. Hope that works. If get does not work, maybe there is another method for this scope.

1 like
armingdev's avatar

Nah m8, still same result. I have tried also this:

        $parts = Parts::with(
            ['cars' => function ($query) {
            $query->select('id', 'name');
        }],
            ['bikes' => function ($query) {
                $query->select('id', 'name');
            }],
            ['formulas' => function ($query) {
                $query->select('id', 'name');
            }]
        )->get();

And Im getting good result (only id and name from cars table), but its only for cars, i have always null at bikes and formulas ..

guc43's avatar
guc43
Best Answer
Level 2

You have to put in one array and not in 3,

$parts = Parts::with(
            ['cars' => function ($query) {
            $query->select('id', 'name');
        },
            'bikes' => function ($query) {
                $query->select('id', 'name');
            },
            'formulas' => function ($query) {
                $query->select('id', 'name');
            }]
        )->get();

did not know select exists :D

2 likes
Thiago_LA's avatar

I try the way you say, but in Laravel 8 return empty array, can you check? thanks.

2 likes
shibbirweb's avatar

You can try this simple syntax

$parts = Parts::with('cars:id,name', 'bikes:id,name', 'formulas:id,name')->get();
5 likes

Please or to participate in this conversation.