Laravel WhereHas and With:

Category: Laravel, Laravel, PHP, PHP

We think you might be interested in this job:

However, Eloquent can “eager load” relationships at the time you query the parent model.

To illustrate the “N+1” query problem, consider a Book model that “belongs to” to an Author model: We can use eager loading to reduce this operation to just two queries.

Yes.Now If you loop over the authors and access the book relationship like so, You will end up with N+1, and to solve it sure you will use with() method to eager load books: Query Result: So far so good, we solve the N+1 issue, but WAIT did you notice something, well I do, the 2nd query gets all books from only the authors that selected from the 1st query, right?

Now, these are the results that we are looking for become: Finally, doing this query over all places and repeating the same conditions, is cumbersome, so we will use a local scope in *Author* model Now, our code is much cleaner by calling it this way: Query Results: Since this query builder may be needed in many Models we will create a macro for it so all Models will have that scope, all you need is to add this snippet under AppServiceProvider::boot()

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners