Laravel Remove Duplicate records from database Table

Using the Laravel Remove Duplicate Records from Database tutorial we will show you how to remove duplicate rows with same column values in Laravel?

Today we work on a project and I need to delete duplicated rows from user_roles table that have the same user_id and have the same role_id.

Here we delete user_roles table duplicate entries to base of user_id and role_id thats we delete one entry will remain in the table and duplicates will be deleted.

use App\Models\UserRole;

$userRoles = UserRole::groupBy('user_id', 'role_id')->get();
$userRolesId = array_column($userRoles ->toArray(), 'id');
UserRole::whereNotIn('id', $userRolesId )->delete();

I hope this example help you.

Leave a Comment