filtering data

Filter Eloquent relationships “on-the-fly”, when you need it

I find more and more Eloquent functions that are rarely used, so continue posting these short tips on the blog. Here’s the next one.

Simple Eloquent relationship goes like this.

And then you get the data in the Controller:

But what if, in some case, you need to get only books that were written this year? Of course, you can change the original relationship, like this:

Notice: did you know about whereYear() function?

Another option is to have a separate relationship function for this:

And then load it like this:

But you probably don’t want to do that because it’s not flexible, so another option is to add filtering query at the time of getting the data.

This is probably the most flexible way – original relationship stays the same, and you use filtering only when you actually needed.

Another related tip to use those internal functions – if you want to use external variables, don’t forget to add use statement. For example, if you want $year to be a variable, this won’t work:

It will throw error and won’t recognize $year.
This is the correct way:

Liked the article? Maybe you need help with your Laravel project?
Our LaravelDaily Team can help!

3 thoughts on “Filter Eloquent relationships “on-the-fly”, when you need it

Leave a Reply

Your email address will not be published. Required fields are marked *