laravel/framework — pull request #4162 by zhuston (2014-04-16 16:48:36+00:00)
Title: Improve query performance of eloquent has() relationship with default count of 1

I really like the eloquent has() method but recently noticed how it is less performant than if I were to write the query myself for the default use case. By default it is looking for >=1 row in which case we don't need to have the DB count all the rows, but just return if it finds one.

If there are just a few rows this isn't a problem but if it is having to count thousands of rows for each record then it is significantly slower.

This feels like a hackish solution but I wanted to get feedback if anyone else has a better idea.

It seems plausible that this solution may interfere with someone's callback so I considered making it conditional on there not being a callback but I couldn't think of a case where the query would be doing anything other than a count(*) in the select since it anticipates returning a single value.