Achraf Ben Soltane
Achraf Ben Soltane

Reputation: 304

Delete unused groups in Laravel 8

I have a group model and I want to delete groups that don't have any member.

How can I get empty groups with eloquent or SQL query ?

class Group extends Model
{
    use HasFactory;
    protected $fillable = [
        'group_name',
        'description'
    ];

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

And this is the User model code:

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use SoftDeletes, Authenticatable, Authorizable, HasFactory, Notifiable;

    public function getNameAttribute()
    {
        return $this->last_name.' '.$this->first_name;
    }

    public function group(){
        return $this->belongsTo(Group::class);
    }
}

Upvotes: 0

Views: 168

Answers (2)

John Lobo
John Lobo

Reputation: 15319

I think whereDoesntHave work in you situation.

 Group::query()->whereDoesntHave('users')->delete();

Upvotes: 1

Flame
Flame

Reputation: 7561

You can use whereDoesntHave:

Group::whereDoesntHave('users')->delete();

You can make sure that you are deleting the correct groups by running this statement instead:

dump(Group::whereDoesntHave('users')->get());

Upvotes: 2

Related Questions