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

kundefine's avatar

with() query method return null

I have a post that post belongs to a user. now I want to get a post with the associate user. but don't want to get all the user column. so in the query->select('*') it will get me all the field. but if I pass any column name in the query->select('user_column_name') of the user it always return null;

$posts = Post::find(1);
$posts()->with(['user' => function ($query) {
                $query->select('*'); // it work
            }])

            ->orderBy('created_at', 'DESC')
            ->take(1)
            ->skip(0)
            ->first();
$posts = Post::find(1);
$posts()->with(['user' => function ($query) {
                $query->select('user_phone', 'user_profile_pic'); // it not working, always return null
            }])

            ->orderBy('created_at', 'DESC')
            ->take(1)
            ->skip(0)
            ->first();
0 likes
2 replies
MichalOravec's avatar
Level 75

You everytime have to select id when you work with relationships by with

$query->select('id', 'user_phone', 'user_profile_pic');
$post = Post::with(['user' => function ($query) {
    $query->select('id', 'user_phone', 'user_profile_pic');
}])->latest()->first();
1 like

Please or to participate in this conversation.