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

hameti's avatar

Help with a simple query

I need to translate the query below in the laravel DB:: query builder. Any ideas please?

SELECT u1.name from users as u1, users as u2 where u1.id<>u2.id AND u1.lastname=u2.lastname;

Please note that I can use Raw() however, I need to paginate and so on that need the query builder.

My try:

DB::table('users')->select('u1.name')->where('u1.lastname','!=','u2.lastname')->where('u1.id','!=','u2.id')->get()->paginate(10);

The issue is probably the assignment users AS u1, users AS u2

0 likes
5 replies
MichalOravec's avatar
Level 75
DB::table('users as u1')->select('u1.name')->join('users as u2', function ($join) {
    $join->on('u1.lastname', '=', 'u2.lastname')->where('u1.id', '<>', 'u2.id');
})->paginate(10);
1 like
hameti's avatar

wow great. If I understand the logic, adding more conditions needs just adding more where to the function. Am I right?

hameti's avatar

Thanks a lot. It now works. I have to remove the comment because it may leak some info. thanks a lot again

Please or to participate in this conversation.