Reputation: 2654
User Migration:
/**
* Users
*/
Schema::create('users', function(Blueprint $t) {
$t->increments('id');
$t->string('email', 100)->unique();
$t->string('password', 60);
$t->string('firstname', 30);
$t->string('lastname', 30);
$t->string('company', 60)->nullable();
$t->string('phone')->nullable();
$t->rememberToken();
$t->timestamps();
});
Role Migration:
Schema::create('roles', function(Blueprint $t) {
$t->increments('id');
$t->string('name', 30)->unique();
});
Pivot Table:
Schema::create('role_user', function(Blueprint $t) {
$t->increments('id');
$t->integer('role_id')->unsigned()->index();
$t->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$t->integer('user_id')->unsigned()->index();
$t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
The relationship is working fine, but I need to retrieve a list of all users who have a particular role, lets say "Agent"
Ultimately I want to add this user list to a Form::select, so I will need only id, firstname, lastname fields from the users table.
OK, After typing all of that, I figured this out. Wanted to still submit in case someone else finds it helpful, or shows me a better way. Below is working:
I first added this to the User model:
public function getFullNameAttribute() { return $this->attributes['firstname'] . ' ' . $this->attributes['lastname']; }
Then I receive prepare the data in the controller:
$agents = User::select('firstname', 'lastname', 'id')->with(['roles' => function($query) {
$query->where('name', 'Agent');
}])->get();
$agentsList = $agents->lists('fullName', 'id');
That seems to work, but I am not sure if it is a proper way to handle it. The page is rarely ever used, so performance wont matter much.
Upvotes: 2
Views: 1252
Reputation: 146191
You may try this, whereHas
will fetch only those with name=Agent
but with will fetch all:
$agents = User::whereHas('roles', function($query) {
$query->where('name', 'Agent');
})->get(['firstname', 'lastname', 'id'])->lists('fullName', 'id');
Upvotes: 2