Search code examples
laravellaravel-5eloquenteloquent-relationship

filter with Eloquent


I have 2 tables: tests, questions and I want to show the activated questions of a test:

$test = Test::whereHas('questions', function(Builder $query){
            $query->where('activated','=','1');
        })->find($id);

but I get the questions; activated and deactivated.

I thank you for your help.


Solution

  • You are fetching all tests, that has activated questions.

    But when getting the resulting $test, you are probably fetching all questions with the relation $test->questions.

    If you want to fetch only activated questions, you can do the following on the $test object:

    $test = Test::whereHas('questions', function(Builder $query){
                $query->where('activated','=','1');
            })->find($id);
    
    $questions = $test->questions()->where('activated', '1')->get();
    

    With the activated questions eager loaded:

    $test = Test::whereHas('questions', function(Builder $query){
                $query->where('activated','=','1');
            })->with(['questions' => function ($query) {
        $query->where('activated', '1');
    }])->find($id);
    
    // Will only give you the activated questions
    var_dump($test->questions);
    

    Or you can define a custom relationship in the Test-model, that does the filtering for you.