Laravel Eloquent Relationships: Lesson 6 of 7

Many to Many

Up Next

Sync

Autoplaying in 7 seconds!

Cancel

Many to many relationships require a pivot table. This is a table that sits between your two tables that you are matching.

We can't just add a foreign key to one of the tables, because that would mean that item only belongs to a single other item.

For instance, we will have a users table, a roles table, and a role_user (Eloquent naming states alphabetical, underscore delimited, singular) table.

Table of Contents

    To create that table:

    php artisan make:migration create_user_roles_table --create=user_roles

    In our case, we used user_roles since it was easier to read.

    Attaching / Detaching

    When we want to add a relationship so that a user is attached to a role, we can do the following:

    $user->roles()->attach($roleId);

    Alternatively, we can remove a role using:

    $user->roles()->detach($roleId);

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.