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

hamzaelmaghari's avatar

Laravel query ->select && ->with

Hello, devs, I usually use ->select method on query with ->with method in order to get only some properties from the model with relation only some properties.

But it doesn't work anymore for me.

Using Laravel 9.51

Here is my query:

Page::query()
            ->orderBy('updated_at')
            ->select('title', 'state', 'created_at', 'updated_at')
            ->get();
1 like
22 replies
webrobert's avatar

with(‘user:Id,name’)

And you need the Id [foreign key] for the select otherwise there is nothing to relate

2 likes
hamzaelmaghari's avatar

@webrobert This is my current model query sorry:

Page::query()
            ->orderBy('updated_at')
            ->select('id', 'title', 'state', 'created_at', 'updated_at')
            ->with('user:id,name')
            ->get();
1 like
webrobert's avatar

@hamzaelmaghari well it works. So either you are missing the relationship or missing the correct related columns

2 likes
hamzaelmaghari's avatar

@MichalOravec

Page::query()
            ->orderBy('updated_at')
            ->select('id', 'title', 'state', 'created_at', 'updated_at')
            ->with('user:id,name')
            ->get();
1 like
MichalOravec's avatar

@hamzaelmaghari User has many pages?

$pages = Page::with('user:id,name')
    ->select('id', 'user_id', 'title', 'state', 'created_at', 'updated_at')
    ->orderBy('updated_at')
    ->get();
2 likes
Snapey's avatar
Snapey
Best Answer
Level 122

@hamzaelmaghari @michaloravec refers to user_id or whatever is the FK on the pages table

Page::query()
            ->orderBy('updated_at')
            ->select('id', 'title', 'state', 'created_at', 'updated_at', 'user_id')
            ->with('user:id,name')
            ->get();

which you need in order to reference the user model

2 likes
Snapey's avatar

@webrobert is correct. I only clarified, and I did it without yet seeing the reply from @michaloravec also giving you the answer and posted a few seconds before my reply, and long after @webrobert posted And you need the Id [foreign key] for the select otherwise there is nothing to relate

1 like

Please or to participate in this conversation.