Eloquent Family Tree — Laravel

Draw the relationships between Eloquent models and watch the PHP take shape: 14 levels of hasMany, belongsTo, belongsToMany and morphTo.

What you learn in this game

A relation is an ordinary method on a model that returns a relation object: $this->hasOne(...), $this->hasMany(...), $this->belongsTo(...) and the rest. Laravel guesses the linking column's name from the model's name, so a column that follows the convention need not be named. The method's name becomes the relation's name: $warga->ktp runs the ktp() method and keeps what it returns. In Mr. Sastro's pavilion every row of the buku induk is a card on the family-tree board, and the relations you write become the red threads between the cards.

The inverse of hasMany is belongsTo: the model that keeps the foreign key points to its owner. $this->belongsTo(Lomba::class) on the Peserta model reads that entry's lomba_id column and fetches one Lomba, or null when there is no race with that number.

One table can be owned by several models at once: each row keeps its owner's type and number. On the owner's side the relation is morphMany (or morphOne), on the owned row's side morphTo. Both name the same relation, and Laravel builds its two columns' names from that name.

When A has many B and B has many C, A can read C directly with one join: a "has many through" relation. Table C does not need a column of A's.

When both sides can have many partners, the pairs are kept in a third table, the pivot, holding two foreign keys. The relation is belongsToMany on both models, and the pivot can be written through the relation: attach, detach, sync.

A morph map maps short names to model classes, so a *_type column does not depend on class names and namespaces. It is registered once as the app starts, usually in a service provider's boot().