ILoveBaymax
ILoveBaymax

Reputation: 267

Laravel 5.0: Pivot table issue

I am an absolute beginner of Laravel framework. I am having an problem that has to do with a pivot table.

I would like to get a collection that is attached with a certain id.

MyController

/**
 * Show the form for creating a new resource.
 *
 * @return Response
 */
public function create(){

    $loggedInUser = \Auth::user();  
    $users = User::lists('first_name', 'id');
    $instructors = // Here comes a collection that has a role_id "2" on the pivot table.
                  //This is where I have no idea what to put 

    return view('courses.create', compact('loggedInUser', 'users', 'instructors'));
}

In this case, I would like to put the collection below in the above variable "instructors" because the collection below has been attached to role_id 2, which is an instructor.

   id: "2",
   first_name: "alex",
   last_name: "powder",
   email: "[email protected]",
   ID: "819763758",
   created_at: "2016-04-18 21:34:12",
   updated_at: "2016-04-19 19:30:48"

$instructor->roles

   id: "2",
   name: "instructor",
   created_at: "2016-04-18 21:34:13",
   updated_at: "2016-04-18 21:34:13",
   pivot: <Illuminate\Database\Eloquent\Relations\Pivot #000000007a61781e00000001381bb0f0> {
           user_id: "2",
           role_id: "2",
           created_at: "2016-04-18 22:54:06",
           updated_at: "2016-04-18 22:54:06"

Role.php

public function users(){
    return $this->belongsToMany('App\User');
}

User.php

public function roles(){
    return $this->belongsToMany('App\Role')->withTimestamps();
}

English is not my first language. If this post does not make sense, please leave your comments. Any advice would be appreciated! Thanks in advance!

Upvotes: 0

Views: 50

Answers (3)

Diptesh Atha
Diptesh Atha

Reputation: 901

For users who has role_id(dynamic) is:

$role_id = 2;

$instructors = User::with('roles')->whereHas('roles', function($q) use ($role_id){ 
      $q->where('role_id', $role_id);
})->get();

Upvotes: 1

Mushangi Derrick
Mushangi Derrick

Reputation: 134

Try this query.

$instructors = User::whereHas('roles', function($query) {
    $query->where('roles.id', '=', 2);
})->get();

Upvotes: 1

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5166

You have to use whereHas if you are looking for users who has role_id 2

    $instructors = User::whereHas('roles', function($q) {
        $q->where('id', 2);
    })->with('roles')->get();

it will bring users who has roles 2

Upvotes: 1

Related Questions