A few helpful gems tucked away in Laravel Eloquent

~ 4 minutes - Published on Jul 5, 2018

Over the last year or so, I’ve been collecting and (sometimes) tweeting about methods and helpers I’ve stumbled across in Laravel’s Eloquent ORM. Most of these aren’t that obvious in the documentation, but have made a huge impact as my applications have grown in both size and complexity.

Here's five of the best examples.

 

Building a query based on conditionals

Code screenshot of building a query based on conditionals

Let’s say you need to query a set of models and rely on external variables to determine what you’re gathering. At first glance you might write a whole query under each of those if statements, which might work but gets a little sloppy and tricky when both (or none) return true. You’d end up with 4 separate eloquent calls for this particular function.

Instead, you can use ->where() on any query after you’ve initially created it. After determining all the conditionals you need to account for, just run ->get() to return the final collection.

 

Using hasOne to return a single object in a hasMany relationship

Code screenshot of using hasOne to return a single object in a hasMany relationship

Have a hasMany() relationship but also need to be able to quickly grab just one item instead of a whole collection? Create a function in your model’s class file that returns hasOne() instead! You can also append additional methods to the call if you want to put any constraints on what you’re returning.

Using ->latest() on the example above returns the item that’s been created most recently.

 

Use where() on a with() by using whereHas()

Code screenshot of using where() on a with() by using whereHas()

This one has a ton of searches for, and articles about, on StackOverflow and other forums. You want to be able to put a constraint on a model’s relationship, and then only return those models whose relationships match that constraint.

The most elegant solution I’ve found to accomplish this is by using whereHas(). This checks that:

  1. The relationship actually exists, and
  2. Allows you to pass a closure that you can use to add constraints to the query being called

In the example above, what ends up getting returned is a collection of User models and their transactions. However, it’s only users who both have transactions, and whose transactions are of the income type.

 

Query date columns using the shorter whereMonth method

Code screenshot of querying date columns using the shorter whereMonth method

Pretty self-explanatory but helpful nonetheless! Instead of using some nested where clauses or looping through the returned collection to breakdown the date and grab only ones from a particular month, eloquent includes a few of these conditional date methods. There’s:

  • whereDate('created_at', '12-31-2017')
  • whereMonth('created_at', '12')
  • whereYear('created_at', '2017')
  • whereDay('created_at', '31')

All of these filter out a collection depending on the date column entered as the first parameter.

 

Only return models if they have a particular relationship using has()

Code screenshot of only returning models if they have a particular relationship using has()

By using ->with() you can call relationship models and lazy-load them alongside the models you’re querying for in the first place. However, if you’d only like to return those models whose relationship actually exists you’ll want to add in the ->has() method before your with call.

Additionally, you can drill down into child and grandchild relationships, as long as they’re separated with a period. For example, if the PostImage model in the above screenshot had a relationship called PostImageComment and I wanted to only return posts that had images and whose images had comments, I’d change the line in the example above to ->has(‘postImages.postImageComments’).

That’s all for now! I’ll be keeping my eyes peeled for more (slightly) hidden helpers scattered around eloquent and Laravel in general.