I have two relationship table. I used with using where to filter records as well as i used wherehas using where to filter records. But can't find the differences between both
-
1Does this answer your question? [Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?](https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean) – Ankit.Z Sep 26 '22 at 10:34
-
Maybe this one can help: https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean – saiful islam Sep 26 '22 at 11:34
3 Answers
If you use where(condition)->with(relation) the query will return the records where condition matches and the relation data if any. Wherase if you use where(condition)->whereHas(relation) the query will return the records where condition matches and where there exists a relation

- 111
- 4
When you use with() with where() condition, you are applying the condition only on the main table not on the related table, but when you use whereHas() this will apply the condition on the relationship, not on the main table. e.g
1) User::with("post")->where('id', 1)->first();
2) User::whereHas("post", function (Builder $query) {
$query->where('status', 1);
})->get();
First will fetch the user who has the user id 1, while second will fetch all the users with posts whose status is published

- 39
- 4
1). Where()
$table::with("relation-name")->where(condition)->get();
simple get the data with this "relation-name"
against this where(condition)
there is no condition apply on the 2nd table (relationship table);
2). Wherehas()
User::where Has("relation-name", function (Builder $query) {
$query->where('status', 1);
})->get();
wherehas() apply condition on the 2nd table (relationship table);
My understanding and also have practiced this way in my projects.

- 59
- 5