Ad

How To Use '::whereHas()' As A Constraint For '::with()' Query When Using Eloquent?

- 1 answer

I have a query:

Posts::whereHas('comments', function($query){
          $query->where('name', 'like', 'asd');
      })->with('comments')->get();

It returns all posts that have comments which have name like 'asd' with all comments of these posts. Can I use the above constraint in '::whereHas' for the 'with' method, so it would not return all comments, but only those that match the requirements? Or do I have to duplicate the query?

Ad

Answer

You can create query something like this, almost without duplicate :)

$callback = function($query) {
     $query->where('name', 'like', 'asd');
}
Posts::whereHas('comments', $callback)->with(['comments' => $callback])->get();

Or, you can make like in this post Laravel - is there a way to combine whereHas and with

Ad
source: stackoverflow.com
Ad