Reputation: 639
I have users, roles
table where each user
have attached one role
in the role_user
table. I need to get in my UserController
all users with role name 'user' associated in role_user
(exclude admins).
I currently have this:
UserController:
class UserController extends Controller {
public function index() {
$users = User::all(); // Get here only users with role 'user' in role_user table
return view( 'admin.users.index' )
->with( 'users', $users )
;
}
}
create_users_table:
class CreateUsersTable extends Migration {
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->string('name');
$table->string('last_name');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
}
create_roles_table:
class CreateRolesTable extends Migration {
public function up() {
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('description');
$table->timestamps();
});
}
}
create_role_user_table:
class CreateRoleUserTable extends Migration {
public function up() {
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->string('user_id')->unique();
$table->integer('role_id')->unsigned();
$table->timestamps();
});
}
}
How can accomplish that?
Upvotes: 0
Views: 1159
Reputation: 862
in User.php Model:
public function roles()
{
return $this->belongsToMany('App\Role');
}
in your controller:
$users = User::whereHas('roles' , function($q){
$q->whereName('user');
})->get();
Upvotes: 1