简体   繁体   中英

Laravel: Get only users with 'user' role from users table

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM