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();
@karagiannidis they do different. First one check id column of assets table, second one - asset_id column
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();
@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!?
@Karagiannidis Ah ok :) Why not check the queries to compare them? :) You can see it using something like debugbar
@Sinnbeck Thanks, checked it with debugbar and they are indeed different as silencebringer explained. Also, the second one is more performant.
@Karagiannidis Exelent. And if they give exactly the same result (I expect they will), then you have your answer :)
Please sign in or create an account to participate in this conversation.