0
votes

Hi I'm using laravel eloquent for my database query. My Problem is that I can't show the data I wanted to show. I have three tables. Say Users Table, Roles Table and User_Roles table.

Users

id | Name |

1 | John |

2 | Doe |

Roles

id | Name |

1 | Admin |

2 | Employee |

3 | Manager |

User_Roles

id | user_id | role_id

1 | 1 | 2

2 | 1 | 3

3 | 2 | 3

Users has Many Roles that is saved in User_Roles table. My query is "I want to show list of Users that has no Employee roles. In the table I want to show only Doe. How can I make it laravel eloquent.

Hope someone can help!

1

1 Answers

1
votes

Define roles relation in User model

public function roles() {
    retrun $this->belongsToMany(\Namespace\Role::class);
}

Retrive the role

$role = \Namespace\Role::where('name', 'Employee')->first();

Get the users

$user = \Namespace\User::whereHas('roles', function($query) use ($role) {
    $query->where('role_id', '!=', $role->id);
})->get();