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

lkmadushan's avatar

Laravel Eloquent whereHas function

Can someone please explain how eloquent whereHas function works? It use a count condition on query. How it works?

0 likes
4 replies
bashy's avatar

You can display the last SQL query with a command (if you wanted to see it)

It JOINS the table and adds a WHERE condition?

If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries:

$posts = Post::whereHas('comments', function($q)
{
    $q->where('content', 'like', 'foo%');

})->get();

Ref: http://laravel.com/docs/4.2/eloquent#querying-relations

lkmadushan's avatar

I can't understand how this query works. Is count statement join tables? Is this more efficient than normal join?

SELECT
 *
FROM
 `products`
WHERE
 (
  SELECT
   count(*)
  FROM
   `categories`
  WHERE
   `products`.`category_id` = `categories`.`id`
  AND `slug` = ?
 ) >= 1
AND `slug` <> ?
bashy's avatar

Try it, run it in MySQL CLI and see the execution time difference :)

1 like
austenc's avatar

The query you posted is a nested select also known as a subquery. So really there are two queries at work here, an outer query and an inner query. Basically, the (inner) SELECT statement evaluates to a boolean value -- this is the reason for the count and the >= 1 condition. Since the inner query results in a true/false value, the outer where clause sees it as just another condition. Hope that helps!

This page explains subqueries in further detail.

Please or to participate in this conversation.