OunknownO OunknownO - 1 year ago 69
MySQL Question

how to access pivot table column

I have bican roles plugin and I need to access over pivot table. This is in my controller code

$users = User::where('role_id','=',2)->get();

migration roles

Schema::create('roles', function (Blueprint $table) {

migration user

Schema::create('users', function (Blueprint $table) {

pivot migration

Schema::create('role_user', function (Blueprint $table) {

Answer Source

If your relation between user and role is many-to-many then it looks that you are querying User incorrectly. The right query will be as:

$users = User::whereHas('roles', function($q) {
                    $q->where('role_id', 2);

Then you can get user's role as:

foreach($users as $user) {
    $user->roles; // returns collection of roles
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download