You can use
DB::select(<your query>)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
At the moment I have a model called contacts and I'm displaying a list of contacts like this:
$contacts = Contacts::orderBy('first_name')->orderBy('last_name')->paginate(200);
return view('contacts/index', ['contacts' => $contacts]);
Now I want to list all contacts which have duplicates, but utilising the same view. So ideally I want to do it via Eloquent rather than Query Builder.
My SQL is:
$sql = 'select * from contacts where id in (select id from conatcts group by concat(first_name,last_name) having count(concat(first_name,last_name)) > 1)'
Is it possible to somehow pass this query to Eloquent and get back an eloquent collection? Note that I also need to use the paginate() method.
I know about the hydrate() method but I am not sure it's possible for me to utilise this inconjunction with the paginate() method.
Thanks!
Okay, I figured it out:
Contacts::whereRaw(<sql>);
In my case:
Contacts::whereRaw('CONCAT(first_name, last_name) IN(SELECT CONCAT(first_name, last_name) FROM contacts GROUP BY CONCAT(first_name, last_name) HAVING COUNT(CONCAT(first_name, last_name)) > 1)')
->orderBy('first_name')
->orderBy('last_name')
->paginate(20);
Please or to participate in this conversation.