Ad

Laravel - Is There A Way To Combine WhereHas And With

- 1 answer

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?

Ad

Answer

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();
Ad
source: stackoverflow.com
Ad