Eloquent Many to Many Relationship

We are going to make roles for our users which will require a new model called Role with a migration

php artisan make:model Role -m

Next you need to make a table for both roles and users. In Laravel you need to use singular case and go in alphabetical order.

php artisan make:migration create_users_roles_table --create=role_user

In your roles migration add the new fields:


In your user role migration add these fields:


Now migrate this

php artisan migrate

Create two roles: administrator, subscriber. Create a second user if doesn’t exist. In role_user attach the user to role based on ID of each. You can do 1,1 and 2,2.

Now we need to define the relationship in the model. Open up User model and add:

    public function roles(){
        return $this->belongsToMany('App\Models\Role');
        //To customize tables name and columns follow the format below
        //(Table name, user foreign key name, role foreign key name)
        //return $this->belongsToMany('App\Models\Role', 'user_roles', 'user_id', 'role_id');

Now let’s see roles in action. Add this to routes:

Route::get('/user/{id}/role', function($id){
    $user = User::find($id);
    foreach($user->roles as $role){
        echo $role->name.'<br>';

Another way to find roles:

Route::get('/user/{id}/role', function($id){
    $user = User::find($id)->roles()->orderBy('id', 'desc')->get();
    return $user;

Leave a Reply

Your email address will not be published.