Member-only story

Avoid The Pain of Repeated Database Queries With Laravel Query Scopes

Kevin Hicks
7 min readSep 12, 2021

--

As you continue building out Laravel apps, you will notice spots that you need to perform the same queries. If your project is like most projects I’ve worked on, you will start with just repeating the query code in many places.

This works great until you need to change the query. Because the query is repeated throughout your code, you now need to change it everywhere. And you might forget to change it somewhere 🤦🏻. This is an enormous maintenance headache. I can’t even count how many bugs I’ve encountered (and written myself) from forgetting to update code in multiple places.

Luckily there are a few easy solutions to reduce duplicate queries.

  • You can move all database code to stored procedures and only interact with the database through stored procedures.
  • Create repository, service, builder, or other classes for your queries.
  • Add methods to the Eloquent model to perform the queries.

All of these solutions will work and have their pros and cons. One solution that is built into Laravel that works well for this is Eloquent Query Scopes. Query scopes provide some advantages over the other methods I mentioned. Three of the most significant benefits are:

  1. It is a first-class…

--

--

Kevin Hicks
Kevin Hicks

Written by Kevin Hicks

Helping other devs evolve & make more money | Senior Developer | 6 Figure Freelancer | Entrepreneur | Build in public | https://kevinhicks.software/

No responses yet