Tales
Tales

Reputation: 1923

Laravel get collection who comply with condition on different model

I have two models:

Class Survey{
    public function steps(){
        return $this->hasMany( Step::class );
    }
}

Class Step{
    public function survey(){
        return $this->belongsTo( Survey::class );
    }

    public function isFinished( Survey $survey ){
        // Check some things
        return ( /* Chech if that step of the survey is finished */ ) ? true : false;
    }
}

In my controller, I want to retrieve all the surveys that have a specific step finished.

public function getFinished( Step $step ){
    $finished = collect();
    $surveys = Survey::all();
    foreach( $surveys as $survey ){
        if( $step->isFinished( $survey ) ){
            $finished->push( $survey );
        }
    }
    return $finished;
}

I know this is not an efficient way to do it. I would like to do it from the model with a static function, so I could do something like:

public function getFinished( Step $step ){
    return Survey::getFinished( $step );
}

Upvotes: 0

Views: 36

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

You can use whereHas():

public function getFinished(Step $step) {
    return Survey::whereHas('steps', function($query) use($step) {
        $query->where('id', $step->id)->where('isFinished', 1);
    })->get();
}

Upvotes: 1

Related Questions