Improving database query performance of polymorphic relations is a rarely-documented edge case in Laravel development but I’ve solved some N+1 problems it presents. A new Collection macro can be introduced, inspired by Illuminate\Database\Eloquent\Collection method load() (L38) that calls Illuminate\Database\Eloquent\Builder method eagerLoadRelations() (L466).

UI showing polymorphic relations

Dashboards, activity feeds, inboxes, and notifications are perfect examples of database tables that hold relationships to many object types. Laravel’s polymorphic relations allow an easy active record representation. But problems arise when nested relations of those morphable relations are referenced.

Here is an example component of a Facebook notification feed, proposed model class names on the right for a Notification@subject() polymorphic relationship.


Recent Notifications

EventInvite Dave invited you to his event Dropping Acid

GroupPhotoUpload Loz added a photo in Cats Driving Cars

GroupPost Hans posted in Fixing N+1 queries

PostLike Nobody liked your political post.


The query to fetch data for this UI might be:

Now suppose to generate the SEO-friendly URL for each notification, that query also needs these nested relations:

  • EventInvite@event()
  • GroupPhotoUpload@group()
  • GroupPost@group()
  • PostLike@post()

Attempting to eager load

will throw an exception since the event() method doesn’t exist on the GroupPost model class, etc.

A hacky eager load attempt using null relationships

This solution is a fugly one but it does attain the end-result. For those missing methods, I added faux relationships that always return an empty collection. So to support the above feed, the GroupPost model would look like:

Then the remaining three model classes also need null relationship methods setup. They’re inexpensive queries but they are being run each page load. It’s a bit bananas and not ideal at all.

A whereNone() scope in the base model class is good for supporting other scopes that accept arguments. When a value isn’t present in the scope’s arguments, sometimes it makes more sense for the query to return nothing rather than whitelisting everything.

whereNone() is as simple as:

A proper solution to polymorphic relation N+1 queries

I was acquainted with Illuminate\Support\Collection as it’s well-documented on laravel.com and I’m often introducing new macros to streamline nasty code chunks. Less well-known is the support-extending Eloquent Collection class that handles models fresh from the database as hashed by keys. Its load() method is exactly what polymorphic relationships need to eager load after the collection is fetched.

Of course a collection pipeline solves all.

Now that above query can be optimized via this macro.

A paginated query looks like: