I'm building out a Shedquarters in my backyard! Check out the ever-evolving post + pictures here →

Ensuring Consistent Polymorphic Relationships with Laravel

October 26, 2020

In a side project that I'm working on, we track the status of licenses for plumbers, electricians, HVAC technicians, along with a whole host of other professions. Each profession has its own license data that we get from various state agencies which means, of course, that every license file has different columns, data formats, levels of specificity, and so on.

We need all of this data combined into a single "licenses" table so that users can search across all licenses at once. Many of our clients employ both plumbers and electricians, or electricians and HVAC technicians. The fact that these licenses come from totally different data sources is an interesting implementation detail, but the users don't care about that, they just want to see:

  • what the status is
  • when it expires
  • what classes need to be taken to renew it

My first thought was to just shoehorn all the disparate data types into a single "licenses" table and be done with it. That would be simple, but we would lose so much source data if we were to do it that way. There are only so many columns that are similar across the various license types, and we like to offer more specific detail on individual licenses whenever we can.

Because we need to keep all the source data, that means that we have to have separate tables for each different license type. But we can't just store the data across a dozen or so tables with no normalized schema, because that would make searching, calculating, and displaying the licenses nearly impossible.

This leads us to our two constraints:

  • Every underlying (source) license record must be kept.
  • Every underlying license needs a normalized representation of itself.

This is the model for what we're describing:

This is a perfect use case for Laravel's Polymorphic Relationships.

If you're not yet aware of polymorphic relations, take a look at this section from the Laravel docs:

A one-to-one polymorphic relation is similar to a simple one-to-one relation; however, the target model can belong to more than one type of model on a single association. For example, a blog Post and a User may share a polymorphic relation to an Image model. Using a one-to-one polymorphic relation allows you to have a single list of unique images that are used for both blog posts and user accounts.

Put simply, polymorphic relationships let you define a relationship that could live in more than one table.

In our case the license model will have an underlying relationship that is the morphed model.

1// License.php
3public function underlying()
5 return $this->morphTo();
Code highlighting powered by torchlight.dev.

And each of the underlying models will have a license relationship that references the normalized version:

1// Underlying models...
3public function license()
5 return $this->morphOne(License::class, 'underlying');

Now we're able to go from $underlying->license and $license->underlying whenever we need to.

In our case, we have about a dozen different underlying models, and we need to be able to enforce some kind of consistency across all those underlying license types.

Adding a Trait

The first thing that we do to ensure consistency across all those underlying models is add an IsUnderlyingLicense trait to each of them. This becomes the vehicle by which we can enforce more consistency down the road.

The trait allows us to co-locate a bunch of common methods and provide a few helpers. The most obvious thing is the license relationship. Since it's going to be the same for every underlying license, we start there.

1trait IsUnderlyingLicense
3 public function license()
4 {
5 return $this->morphOne(License::class, 'underlying');
6 }

Now every model has the relationship defined. Easy enough.

One really nice thing that Laravel does with regard to traits is that it gives you an opportunity to "boot" a trait on a model. If you add a boot[TraitName] method, Laravel will call that as the model is booting. This is a perfect spot for you to hook in and provide extra functionality to your trait.

In our case, we're going to do a little bit of MorphMap introspection.

Ensuring the MorphMap

Laravel gives us the ability to register a MorphMap so that the database is not tightly coupled to class names. I prefer to always register a morph map, because then I don't have to worry about refactoring my classes later. I also like to make my types integers instead of strings, but that's just a personal preference.

In our IsUnderlyingLicense trait, we can add some assurance that each underlying license is registered in the morph map. We do this by checking if the getMorphClass is the same as the class name. If it is, we know that we haven't registered it in the map:

1trait IsUnderlyingLicense
3 public static function bootIsUnderlyingLicense()
4 {
5 if ((new static)->getMorphClass() === static::class) {
6 throw new Exception('Relation morph not mapped for ' . static::class);
7 }
8 }

Laravel will call this method automatically when booting the model, and throw an exception if this particular underlying license is not registered in the map. Now I'll never forget to set up the map whenever I add more underlying types in the future.

1// AppServiceProvider.php
3 1 => LicensePlumber::class,
4 2 => LicenseHVAC::class,
5 3 => LicenseElectrician::class,
6 // etc...

Enforcing a Contract

Speaking of forgetting to do things in the future... adding abstract methods in the IsUnderlyingLicense trait is a great way to enforce a contract on the underlying licenses. For our application, we have one abstract method called spawn that is responsible for generating the normalized license model.

1trait IsUnderlyingLicense
3 abstract public function spawn();

Anytime I make a new underlying license, my editor is going to let me know that I need to implement the spawn method.

This gives full responsibility to the underlying license as to how the normalized license should be created. It also means that at any point I want I can blow away the licenses table and re-spawn them all from the underlying data.

Of course, we can also provide helper methods to those underlying licenses. We have a spawnSuperLicense method that does some boring work on behalf of the underlying licenses:

1trait IsUnderlyingLicense
3 abstract public function spawn();
5 public function spawnSuperLicense($attributes)
6 {
7 $attributes = array_merge($attributes, [
8 'normalized_at' => now(),
9 ]);
11 $license = License::updateOrCreate([
12 'underlying_type' => $this->getMorphClass(),
13 'underlying_id' => $this->id,
14 ], $attributes);
16 return $license;
17 }

Iterating Every Underlying Class

Whenever we load new source data into the underlying license tables, we then need to go through every type of underlying license and spawn new normalized licenses.

To make sure we don't miss any in the future, we have added an each helper that finds all those classes for us.

1trait IsUnderlyingLicense
3 public static function each($callback)
4 {
5 // Find all the files that start with "License"
6 $models = (new Finder)->in(app_path())->name(['License*'])->files()->depth('< 1');
7 $models = iterator_to_array($models);
8 shuffle($models);
10 foreach ($models as $model) {
11 $class = "App\\" . head(explode('.', $model->getBasename()));
13 // See if the class has the IsUnderlyingLicense trait.
14 if (!class_has_trait($class, self::class)) {
15 continue;
16 }
18 // Callback if so.
19 $callback($class);
20 }
21 }
Code highlighting powered by torchlight.dev.

Now, looping through every class becomes as simple as:

1// Commands/Normalize.php
3public function handle()
5 IsUnderlyingLicense::each(function($class) {
6 $class::needsNormalizing()->get()->each->spawn();
7 });

It's nice to have that as a convenience, but more importantly we never have to remember to come back and update the list of underlying licenses.

Sharing Scopes

The eagle-eyed reader will note that there must be a needsNormalizing scope in every underlying license for the code above to work properly. The scope lives in that trait as well:

1trait IsUnderlyingLicense
3 public function scopeNeedsNormalizing($query)
4 {
5 $table = $query->toBase()->from;
7 $query
8 // There is no super license at all.
9 ->whereDoesntHave('license')
10 // Or the underlying license has a was updated more
11 // recently than the normalized license.
12 ->orWhereHas('license', function ($sub) use ($table) {
13 $sub->whereColumn("$table.updated_at", '>', 'licenses.normalized_at');
14 });
15 }

(Note: that's an abbreviated version of the scope. I'll do a write-up soon of all that goes into normalizing abnormal data. It's... a lot.)

Ensuring Columns via Tests

There are a few common columns that we want to store at the underlying license level as opposed to the normalized level, so we need a way to enforce that those columns exist.

I've found that the easiest way to do this is by adding a list of columns you need to ensure to the trait, and then using a test to verify they are there.

First we'll add the list of columns to the trait:

1trait IsUnderlyingLicense
3 public static $ensureColumnsExist = [
4 'data_fetched_at'
5 ];

and then we'll create a relatively simple test:

1class AllUnderlyingLicensesHaveColumnsTest extends TestCase
3 use RefreshDatabase;
5 /** @test */
6 public function they_have_the_columns()
7 {
8 IsUnderlyingLicense::each(function ($class) {
9 $table = (new $class)->getTable();
10 $columns = collect(DB::select("SHOW COLUMNS from $table;"))->keyBy('Field');
12 foreach (IsUnderlyingLicense::$ensureColumnsExist as $column) {
13 $this->assertTrue(
14 $columns->has($column),
15 "$table does not have the $column column."
16 );
17 }
18 });
19 }

We loop through every underlying license and get all of the columns as they currently exist in the database and then compare them to the columns listed in the trait. If a particular underlying license doesn't have one of the columns, then the test will fail.

Again, nothing to remember!

The Final Word

Everything we've done here is to give ourselves confidence that we won't muck anything up in the future. Often times in scenarios like these, a lot of knowledge is stored in the head of the person or people that originally made the structure.

Instead, try to make as much of that explicit as possible, as a kindness to your future self and coworkers.

Thanks for reading! My name is Aaron and I'm currently working at small property tax firm in Texas, where I serve in dual roles as COO & CTO.

I work on a lot of projects. I'm building a shedquarters. I currently do a podcast, and I used to do a different podcast.

If you ever have any questions or want to chat, I'm always on Twitter
Copyright 2013 - 2021, Aaron Francis.