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!💻

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay