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

PKarag's avatar

eloquent whereHas query variation

Hello everyone,

These 2 snippets below seem to achieve the same thing. Which one do you think has the proper syntax and why?

1:

$user = User::whereHas('assets', function ($query) {
					$query->where('assets.id', request()->query('asset_id'));
})->first();

2:

$user = User::whereHas('assets', function ($query) {
					$query->where('asset_id', request()->query('asset_id'));
})->first();
0 likes
6 replies
Sinnbeck's avatar

Is the asset_id on the users table? If so, why do you need the whereHas() ?

$user = User::where('asset_id', request()->query('asset_id'))->first();
PKarag's avatar

@Sinnbeck Thanks for your answer. No, it's a many-to-many relation.

@silencebringer Thanks for your answer. So, if I understood correctly, the first one checks the assets table and the second one checks the pivot table? So it makes more sense to use the second one!?

Sinnbeck's avatar

@Karagiannidis Ah ok :) Why not check the queries to compare them? :) You can see it using something like debugbar

PKarag's avatar

@Sinnbeck Thanks, checked it with debugbar and they are indeed different as silencebringer explained. Also, the second one is more performant.

Sinnbeck's avatar

@Karagiannidis Exelent. And if they give exactly the same result (I expect they will), then you have your answer :)

Please or to participate in this conversation.