Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

HOVO's avatar
Level 1

How to delete all users who have same role

Hello everyone i am beginner on laravel so lets imagine i have roles and users table when deleted for example admin role on roles table need delete all users who have admin role i use many to many relationship

  Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

 Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('role');
            $table->timestamps();
        });

 Schema::create('role_user', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->unsignedBigInteger('role_id');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
        });

Models

 public function roles(){
        return $this->belongsToMany(Role::class)->withTimestamps();
    }

 public function users(){
        return $this->belongsToMany(User::class)->withTimestamps();
    }

Please help me about that :3

0 likes
1 reply
MichalOravec's avatar
$role = Role::where('role', 'admin')->firstOrFail(); // just an example

$role->users()->delete();

$role->delete();

Or if you need to run events

$role = Role::with('users')->where('role', 'admin')->firstOrFail(); // just an example

$role->users->each->delete();

$role->delete();
1 like

Please or to participate in this conversation.