mardi 11 septembre 2018

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 );
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2O8We5p
via IFTTT

Aucun commentaire:

Enregistrer un commentaire