Laravel Eloquent: When To Constrain Eager Load or To Use Relationship Existence — Make Search Query

Photo by Ilya Pavlov on Unsplash
DB scheme
$return = User::where(‘status’, ‘active’)->with(‘profile’, ‘photos’)->get();
$return = User::where(‘status’, ‘active’);
if($request->has(‘filterByAge’){
$return = $return->where(‘age’, ‘=’, $request->filterByAge);
}
$return = $return->with([‘profile’, ‘photos’]);
$return = $return->get();
$return = $return->with([‘profile’ => function($query){…}, ‘photos’]);
$return = $return->has(‘profile’)->has(‘photos’, ‘>’, 0);
$return = $return->get();
use Illuminate\Database\Eloquent\Builder;public function searchByParams(Request $request)
{
$return = User::where(‘status’, ‘active’);
if($request->has(‘filterByAge’){
$return = $return->where(‘age’, ‘<=’, $request->filterByAge);
}
$return = $return->with(‘profile’, ‘photos’)
$return = $return->whereHas('profile', function(Builder $query) use($request){
if($request->has('height'){
$query = $query->where('basic->height', '<=', $request->height);
}
// you can add more filters here with the condition you need.
// as long as you don't forget to return the $query.
return $query;
});
$return = $return->paginate(25);
return response()->json($return);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store