Using "with" in eloquent query

This is generally used for eager loading for associated model in the main model which solves N+1 query problem.
So, It is used when some associated models need to be preloaded with main model.
Thus, Eager loading helps to run those associated model queries only once instead for all those (associated) model rows in the collection thus solving the N+1 query problem.

Example:

Community -> hasMany -> Topic

$communities = Community::with('topics')->get();
foreach( $communites as $community ){
  // Here since topics is preloaded, there will not be any additional query
  $community->topics
  // if you want some more filtering in topics, it can be done like following 
  $community->topics->whereIn('id', [2,3,4]);
}

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent