DEV Community

Sabber Hossain
Sabber Hossain

Posted on

Laravel Tip: whereHas or whereRelation?

Welcome to my Laravel tips and tricks. We are going to learn about eloquent usage and its limitation with strength.

Scenario:
I have user and order table from where i need to pull those user orders which status is “completed”. Before Laravel 8, We used “whereHas” to compare any column value from related tables. But things were getting easier when Laravel 8 introduced “whereRelation” eloquent relation first.

Image description

Wow! Pretty shorter and easy syntax! 😯

Facts and Limitations:
Sometimes we think, whereRelation has better performance than whereHas. But we are wrong! While converting eloquent to SQL, I found both execute same query:

/-- whereHas query --/

select * from `users` where exists 
  (
    select * from `orders` 
    where `users`.`id` = `orders`.`created_by` 
    and `status` = ? 
    and `orders`.`deleted_at` is null
  ) 
and `users`.`deleted_at` is null
Enter fullscreen mode Exit fullscreen mode

/-- whereRelation query --/

select * from `users` where exists 
  (
    select * from `orders` 
    where `users`.`id` = `orders`.`created_by` 
    and `status` = ? 
    and `orders`.`deleted_at` is null
  ) 
and `users`.`deleted_at` is null
Enter fullscreen mode Exit fullscreen mode

So, It’s up to you that what you should use in where because whereRelation has limitation. When you want to check more than one condition you have to use “whereHas” because “whereRelation” only used for related single condition. For multiple condition whereHas use iterative condition in one subquery where whereRelation iterative subquery for each condition check in related table which isn’t totally feasible! 😒

Image description

So, think before you apply eloquent method for code maintainability. Happy Coding!💻

Top comments (0)