sleepless
sleepless

Reputation: 1789

Laravel - is there a way to combine whereHas and with

I'm currently facing a small problem. I want to return a model only if a relation with certain conditions exists. That's working fine with the whereHas()-method.

$m = Model
    ::whereHas(
        'programs',
        function($q) {
            $q->active();
        }
    );

However, calling the relation as a property like this will give me all (not filtered results).

$m->programs;

So basically what I'm doing now is this:

$m = Model
    ::whereHas(
        'programs',
        function($q) {
            $q->active();
        }
    )
    ->with(array('programs' => function($q) {
        $q->active();
    }))
;

That's working fine but I feel very bad about doing the same thing again. That can't be the right way. How can I achieve this without kind of duplicating the code?

Upvotes: 3

Views: 3090

Answers (2)

MoishyS
MoishyS

Reputation: 2882

In Laravel 9.17 withWhereHas

Example:

   $a= Model::withWhereHas('programs', function ($query) {
      $query->active();
    })->get();

Check out the documentation for more information.

Upvotes: 1

Anže Časar
Anže Časar

Reputation: 404

If a concept of an "active program" is important in your application, consider creating a separate relation just for active programs (in this case I'm presuming you have a HasMany relation):

class Model
{
    public function activePrograms()
    {
        return $this->hasMany(Program::class)->active();
    }
}

Then you can simplify your query to:

Model::with('activePrograms')->has('activePrograms')->get();

Upvotes: 7

Related Questions