21. Module Communication. Laravel Morph Relations. Eloquent Trait. Decorator. OneOfMorphToMany relation

Video version
(Leave your feedback on YouTube)

Polymorphic Relations

Polymorphic relations in SQL allow one table to relate to any number of other tables through a field that stores object identifiers from different tables and a field that indicates the table.

Polymorphic relations are ideal for database isolation within a module.

A few personal tips when working in Laravel:

  • NEVER use ClassName as a table pointer. Always use an alias:
enforceMorphMap
Relation::enforceMorphMap([
    'alias_name' => SomeModel::class,
]);
  • able suffix is recommended but inconvenient. I advise standardizing and using the same name for all polymorphic examples, such as entity_id, entity_type.
  • I also recommend standardizing the relations table. My option is has_relations for basic cases.
  • If you use Postgres, I recommend formatting aliases in an Enum, even if there is only one relation now. This will provide optimization and, most importantly, understanding in the code and DB with which entity it can interact.

Within a module - use any relations. Between modules - polymorphic.

Migration
DB::unprepared("CREATE TYPE some_holder AS ENUM ('some_use_table1', 'some_use_table2')");

Schema::create('has_device', function (Blueprint $table) {
    $table->foreignId('some_id')->constrained();
    $table->foreignId('entity_id');
    $table->typeColumn('some_holder', 'entity_type');
    $table->index(['entity_id', 'entity_type']);
    $table->unique(['device_id', 'entity_id', 'entity_type']);
});
  • Don't forget to add an index for entity_id, entity_type. I also advise making the combination of device_id, entity_id, entity_type unique - all repetitions go in the payload.
  • Remember, one of many relations in the case of eager loading (with) pull all records and attach one to the request.
  • Create extra morph relations if necessary. This can simplify logic and code understanding and, of course, optimize selections.
  • The database does not guarantee the integrity of morph keys! Keep this in mind.
  • The DB cannot implement cascading deletion of polymorphic relations. The responsibility for deletion lies with the developers. Do not confuse detach and deletion for MorphManyToMany. Detach can be done immediately (but should not be), and delete only when there are no other references to the object.
  • Laravel does not support OneOfMorphToMany, but it is easy to implement. Be careful. This approach pulls ALL records and returns only one. I advise you to use only with a unique key $table->unique(['entity_id', 'entity_type'])

Eloquent Trait with Relations and Scope Approach for Module Interaction - Decorator

The approach involves isolating all relation code in a trait. This works only in ActiveRecord. Doctrine will not handle this as the model file defines the DB, not the other way around.

Formally, the approach has no name. Although it is used in many ready-made solutions. But if you slightly lower the formalities - this is literally a Decorator.

I recommend calling the approach a decorator, so the working principle is clearer, and you personally look smarter than when you call it "well, that trait."

For implementation, it is very important to understand the principle of the with method of QueryBuilder. The principle is very simple, but for some reason, many do not understand it:

  1. with takes all keys from the main query. Therefore, id in the select query is mandatory.
  2. Makes a query to the related table, pulling out only the records that are related to the entities from the main query - where entity_id in (ids) where entity_type = 'some_type''.
  3. Then on the code side, each model binds the related models to each object. Therefore, pulling id for select relation is mandatory.

Thus, the with query is always +1 simple select query. There will be no n+1 problems; this is Eager loading.

Not only in with, but everywhere, write SELECT and specify the list of fields you want to retrieve. This is optimization, code readability, and code security. `Select *` is an antipattern even when retrieving one record. Use `->first(['id'])` if you need an object. Or `->value('id')` - when you need a specific field.

A personal recommendation is to write the list of fields in select immediately with the table specification. This will greatly simplify navigation through the code and allow free use of join.

It is important to understand the principle of eloquent scoped methods. Here everything is simple - these are methods on QueryBuilder. A method without the scope prefix can be used as part of the selection query.

For the trait approach, you need to isolate:

  1. Function describing the relation. Ideally a morph relation. Mandatory.
  2. Scope functions for retrieving related data. This will standardize data for all who use the relation. And will allow reusing the selection and testing it in isolation.
  3. Scope functions for filtering. where has etc.
  4. Scoped functions for aggregation. Count, sum, etc. Again, it isolates and allows describing exceptions from logic.
  5. Functions attach, detach, set, etc. This will allow isolating any specific save logic inside the trait. And, of course, test it.

For trait names, I also recommend abandoning the able prefix. HasSomeRelation will be ok.

Combine decorator and JsonResource. This very conveniently allows isolating and describing response formats.

For simple entities, usually, one resource is enough. For complex ones - 2: short for lists and more detailed. If you have a lot of resources - most likely you have problems with business logic. And the frontend developer will curse you.

The Trait approach works perfectly with simple relations where the main entity and its dependencies are obvious. Problems start when entities are equal. For example, a music band and concerts - a direct dependency, the band has concerts. But for a pair of music band and festival, it is hard to say who depends on whom. This is the chicken and egg problem, and no approach solves it beautifully.

For multi-layered relations, I advise denormalizing. Yes, it sounds scary, but in practice attaching an "order" to both the customer and the store at once - this is literally 2 lines of code and plus one simple record in the DB. But it will provide incredible convenience in work and optimization.

A big minus of such relations is the complexity of testing. Methods that pull and filter many scope methods from different traits will often be encountered. Here, either really create a full structure with entities or simply call a conditional ModelEvent on scope methods and check their call.

Action for communication

Of course, instead of scope methods, you can use Action with the same logic as with, but implemented manually. And this will have to be done when moving the module to a separate service. But for now, I think it is more convenient to limit everything to a trait.

Complex logic, large Query requests, etc. should still be moved to Action. Testing them is much easier.

An advantage of Action is the ability to call them in a queue, for example, saving relations. But this is very bad for user experience. I do not recommend it.

Polymorphic relations will still be the only adequate DB structure, regardless of whether you use decorators or actions.

Transactions

Transactions are mandatory in the context of denormalization.

And without it, a transaction gives 2 very positive points:

  1. You save everything or nothing. You will forever get rid of data integrity problems in case of errors. Even when using microservices, a throw from action will say that everything is not ok.
  2. The transaction creates one connection to the DB. This is somewhat irrelevant for Octane but gives a significant effect in normal development.

Always test transactions. It is very easy to forget to call commit, and debugging this is very difficult.

Test transaction example
 /**
 * @test
 */
public function canHandleTransactionError(): void
{
    $user = User::factory()->create();
    $this->actingAs($user);

    DB::shouldReceive('beginTransaction')->once();

    DB::shouldReceive('commit')
        ->once()
        ->andThrow(ModelNotFoundException::class);

    DB::shouldReceive('rollBack')
        ->once();

    $this->deleteJson('/api/v1/sessions')
        ->assertStatus(404);
}