Vidol Chalamov
Vidol Chalamov

Reputation: 73

Filtering laravel collection with eloquent relation

I have a question about filtering in Laravel collection.

Here is the case: I have Test model where I have eloquent relation hasMany with Question model. In my index method in TestController I want to take only tests that have 3 or more questions.

$tests = Test::where(function($test) {
    return $test->questions->count() > 3;
})->get();

Something like code below, but obviously that wont work.

Thank in advance.

PS: This is my first question in stackoverflow, sorry for bad English...

Upvotes: 3

Views: 1645

Answers (1)

Roy  Developer
Roy Developer

Reputation: 122

$tests = Test::has('questions', '>=', 3)->get();

for more info read Laravel Docs

Upvotes: 6

Related Questions