Defining Relationships: Many To Many

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}
Return $this->belongsToMany('App\Role', 'role_user');
Return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}
$roles = App\User::find(1)->roles()->orderBy('name')->get();

Defining The Inverse Of The Relationship

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

Retrieving Intermediate Table Columns

$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}
Return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
Return $this->belongsToMany('App\Role')->withTimestamps();

Customizing The pivot Attribute Name

Return $this->belongsToMany('App\Podcast')
                ->as('subscription')
                ->withTimestamps();
$users = User::with('podcasts')->get();

foreach ($users->flatMap->podcasts as $podcast) {
    echo $podcast->subscription->created_at;
}

Filtering Relationships Via Intermediate Table Columns

Return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

Defining Custom Intermediate Table Models

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User')->using('App\UserRole');
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserRole extends Pivot
{
    //
}

Defining Relationships: Many To Many — Structure map

Clickable & Draggable!

Defining Relationships: Many To Many — Related pages: