Junior Grossi has a tutorial posted to his site for the Laravel (well, Eloquent) users out there showing how to work with querying and eager loading complex relationships to access the data from your database.
Laravel is a PHP framework that uses Eloquent, a powerful and amazing ORM that allows you to do complex SQL queries in a very easy way. But sometimes you need more, and here I’m gonna give you an interesting tip that can bring you a lot of flexibility.
He sets up the situation where, as an application grows its needs for interaction with the data evolves and becomes more complex. Laravel (Eloquent) comes equipped with some tools that can help with this. To illustrate, he outlines a basic "blog" application with Post
and Comment
types and their relations. While it's simple to get the comments for a post, querying them can get a little more complex. He provides some examples using whereHas
/orWhereHas
but points out an issue with the results (all comments are returned, not just the ones matching the queried posts).
The solution he proposes is to eager load them instead. His example code still uses the whereHas
but adds the comments to a temporary variable which is then filtered via a with
on the query.