Ishtiaq Ahmed
Ishtiaq Ahmed

Reputation: 294

Eloquent: filter only rows which has related “children” rows

I want to filter only those categories which have at least one product. I write Category::with('products')->… but how do I filter out those empty categories? Those with no product?

app\Category.php:

class Category extends Model {

    // ...

    public function products() {
        return $this->hasMany('App\Product');
    }

    // ...

}

app\Http\Controller\CategoriesController.php:

function getIndex() {
    $categories = Category::with('products')->get();
    return view('categories.index', compact('categories'));
}

Upvotes: 0

Views: 495

Answers (3)

user19794767
user19794767

Reputation:

Us the has function

Category::with('products')->has('products')->get()

Upvotes: 1

Ishtiaq Ahmed
Ishtiaq Ahmed

Reputation: 294

I have found solution..

There’s an app function for that: has().

app\Http\Controller\CategoriesController.php:

function getIndex() {
    $categories = Category::with('products')->has('products')->get();
    return view('categories.index', compact('categories'));
}

Upvotes: 0

Dilip Hirapara
Dilip Hirapara

Reputation: 15306

You can use has in it

$users = Category::has('products')->get();
// only Categories that have at least one product are contained in the collection

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Upvotes: 2

Related Questions