Laravel 5: Eloquent – relationship types: many to many

Eloquent: relationship types – many to many

DB tables used in examples: here.

many2many

Many-to-many:
This relation defines many to many situation.
Posts can have more than one tag, e.g. it could be described by tags: laravel, framework, php etc.
But also given tag can describe more than one post, e.g. tag ‘laravel’ could describe dozens of posts about Laravel.
Pivot table

This kind of table usually has only 2 fields (columns) and each holds primary id for each pivoted table as a foreign key.
Lets see this image:

many2many2

So, when create pivot table, the general idea is to prefix ‘_id‘ with lower case of pivoted model name.
e.g. in this case we pivot models: POST and TAG, so we get post_id and tag_id.

Laravel also expects pivot table to named by taking alphabetically lowercase names of pivoted models.
In our case, we would get this name: post_tag.

Of course you can have custom names for foreign keys in pivot table and you can name pivot table anything you want, but then you have to specify them in method belongsToMany() – read below.

Post can have MANY tags and vice versa: belongsToMany()
base notation

explanation:
ModelName in this case is: Post, or Tag – depending, in which we use this.

  • method location – one method is located on each of joined models
  • argument #1 – object name
    It can be given as:

    • object name with path: App\Models\ModelName
    • object name: ModelName – required use App\Models\ModelName
    • class name: ModelName  – required use App\Models\ModelName
  • argument #2pivot_table
    This table is used to join models involved – read more above in section about pivot table.
  • argument #3 and #4 – foreign_key_defined_model / foreign_key_joined_model
    This is one of foreign keys – as third, you usually give foreign key from pivot table, that belongs to model you place method belongsToMany().
    example: if method belongsToMany() is defined on model Post, then foreign_key_defined_model is ‘post_id‘ and foreign_key_joined_model is ‘tag_id‘ as this is a joined model.
    When you place belongsToMany() on model Tag, then you switch foreign_key_defined_model to ‘tag_id‘ and foreign_key_joined_model to ‘post_id‘.
how it looks like – example:
POST model:

 TAG model:

how to use it
Access data via Post object.
We can use Eloquent dynamic property.

Access data via Tag object.
We can use Eloquent dynamic property.

Extra columns in pivot table

Timestamps maintenance

If your pivot table has timestamps and you want to maintain them automatically, do this:

If you want to add constraint using extra pivot tables, use this:

If you are comparing against array use this:

It works like in_array().