Why not using eloquent relationships?
Querying speed depends on how you database is organized. By indexing contact_type it could speed up a bit.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Below query is taking approx 7 to 8 seconds. I think self join in laravel is taking too much time when there is huge rows. any suggestion? table has 48000 recoreds.
$excludeUser = [1,2,3];
$userIds = [5,6,8,9,8];
\DB::table('usr_contacts as uc1')
->select('uc1.contact_id as uid', 'uc2.contact_id as id')
->join('usr_contacts as uc2', function ($join) {
$join->on('uc1.user_id', '=', 'uc2.contact_id');
$join->on('uc1.contact_id', '=', 'uc2.user_id');
})
->whereIn('uc1.user_id', $userIds)
->whereNotIn("uc1.user_id", $excludeUser)
->whereNotIn("uc2.user_id", $excludeUser)
->where('uc1.contact_type', 'LIKE', '%User%')
->where('uc2.contact_type', 'LIKE', '%User%')
->whereNotNull('uc1.id')
->whereNotNull('uc2.id');
Please or to participate in this conversation.