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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay