Multi-level has() query in laravel

Multi-level has() query in laravel

Published On: May 19th, 2023

When retrieving records from the database, sometimes we may require fetching those categories which has product, and this can be achieved by simply.
Let's suppose:
One to Many relationships between category and products.
One to Many relationships between product and feedbacks.

$categories = Category::has('products')->get();

But what if we are supposed to retrieve those categories that has product with feedbacks?

$cateogries= Category::has('products.feedbacks')->get();

It's that easy.

Note: You should have a method named products to define hasMany() relation for the product in Category Model and feedbacks method to define hasMany() relation for feedbacks.

Reference:
One to Many
Query Relationship