Laravel - Relationships - Many To Many Model Structure

Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method. The belongsToMany method is provided by the Illuminate\Database\Eloquent\Model base class that is used by all of your application's Eloquent models. For example, let's define a roles method on our User model. The first argument passed to this method is the name of the related model class:

    
    belongsToMany(Role::class);
        }
    }
	

Once the relationship is defined, you may access the user's roles using the roles dynamic relationship property:

    
    use App\Models\User;
    
    $user = User::find(1);
    
    foreach ($user->roles as $role) {
        //
    }
	

Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the roles method and continuing to chain conditions onto the query:

    
    $roles = User::find(1)->roles()->orderBy('name')->get();
	

To determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:

    
    return $this->belongsToMany(Role::class, 'role_user');
	

In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:

    
    return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');