KristofMorva
KristofMorva

Reputation: 649

Merge 'with' and 'whereHas' in Laravel 5

I have this code in Laravel 5, using Eloquent, which is working perfectly:

$filterTask = function($query) use ($id) {
    $query->where('taskid', $id);
};

User::whereHas('submissions', $filterTask)->with(['submissions' => $filterTask])->get();

Basically the goal is to get only those users with their filtered submissions, which has any of them. However, it seems wasting to run both whereHas and with methods with the same callback function. Is there a way to simplify it?

Thanks.

Upvotes: 27

Views: 29383

Answers (4)

black_belt
black_belt

Reputation: 6799

You can now achieve that In Laravel 9.17

Example:

use App\Models\User;

$users = User::withWhereHas('posts', function ($query) {
  $query->where('featured', true);
})->get();

Check out the documentation for more information

Upvotes: 4

Ijas Ameenudeen
Ijas Ameenudeen

Reputation: 9259

The 'macroable' way (Laravel 5.4+)

Add this inside a service provider's boot() method.

\Illuminate\Database\Eloquent\Builder\Eloquent::macro('withAndWhereHas', function($relation, $constraint){
    return $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
});

Upvotes: 5

Emsal
Emsal

Reputation: 107

I want to extend the answer from @lukasgeiter using static functions.

public static function withAndWhereHas($relation, $constraint){
    return (new static)->whereHas($relation, $constraint)
        ->with([$relation => $constraint]);
}

Usage is the same

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

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152900

In terms of performance you can't really optimize anything here (except if you were to move from eloquent relations to joins). 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]);
}

Usage:

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

Upvotes: 73

Related Questions