How to reduce code duplication with relationships in Laravel

Categorized as Laravel Tagged

Since Laravel 9.16 we can reduce the code a bit, using withWhereHas() method. It’s time to do some code clean up! See the example below:

// Before
Store::whereHas('products', function ($query) {
  $query->where('enabled', true)->where('sale', true);
})->with(['products' => function ($query) {
  $query->where('enabled', true)->where('sale', true);
}]);


// After
Store::withWhereHas('products', fn ($query) => $query->where('enabled', true)->where('sale', true));

As Laravel contributor Eusonlito describes:

There are a lot of times that we need to load a relationship using with with the same conditions that we use for whereHas. This method simplifies this selection by avoiding repeating the code used both to filter with whereHas and then to select that same record using with. There is less code, it is more readable and easier to maintain

Leave a reply

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