Combining whereHas and with in laravel Eloquent

amrit shrestha
Feb 25 · 1 min read

With or without whereHas, two queries will be run. One to select all users another one to load the related models. When you add the whereHas condition a subquery is added, but it's still two queries.

However, syntactically you could optimize this a bit by adding a query scope to your model (or even a base model if you want to use this more often):

public function scopeWithAndWhereHas($query, $relation, $constraint){
return $query->whereHas($relation, $constraint)
->with([$relation => $constraint]);


User::withAndWhereHas('submissions', function($query) use ($id){
$query->where('taskid', $id);

If you don’t want to add a scope, like above you can do something like this as well

$callback = function($query) {
$query->where('something', '=', 'something');
$submissions = Post::whereHas('submissions', $callback)->with(['submissions' => $callback])->get();