restart93's avatar

Help Select 3 columns from eloquent and 2 columns from related model

$articles = Article::with(['user' => function ($query) {
            $query->select('id', 'name', 'avatar');
        }])
            ->select('id', 'title')
            ->take(30)
            ->get();

I get good queries (I check with DB::enableQueryLog(); ) but the result is

[
	{
		"id": 1,
		"title": "article title 1",
		"user": null
]

If I don't use select I get user but a lot of fields on main model

[
	{
		"id": 1,
		"title": "article title 1",
		"created_at": "2023 05-05 20:00:00",
		"user": {
			"id": 1,
			"name": "user1",
			"avatar": "ava.jpg"
		}
	}
]
0 likes
2 replies
DhPandya's avatar
DhPandya
Best Answer
Level 12

@restart93 Add user_id in your Article select statement.

$articles = Article::with(['user' => function ($query) {
            $query->select('id', 'name', 'avatar');
        }])
            ->select(['id', 'title','user_id'])
            ->take(30)
            ->get();
2 likes

Please or to participate in this conversation.