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);
}

--

--

--

A full-time husband and dad who like to code for some money. Currently being entrusted as an Engineering Manager at an awesome team.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Live PDF experimentation

CS373 Spring 2022: Elliot Sims

10 ideas to improve your Gradle build times [Part II]

Section 6 — Summary A11 — Reinvent yourself in human relationships

BLOG “AS MY PORTUGUESE GRANDFATHER USED TO SAY”. Reinvent yourself in human relationships. REINVENT YOURSELF IN THE COVID-19 ERA. By José Antonio Ribeiro Neto (Zezinho). #reinventyourself #selfimprovement #socialnetwork #socialmedia #graph #networking #sixdegreesofseparation #graphtheory #relantionships #dunbartheory

8 Life Lessons a Programmer with 30+ Years of Experience Taught Me

Alright Kangaroos,

Notification when Someone Logs into your Amazon AWS Console

5 Ways We Use BetterCloud at BetterCloud: A Love Story

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
Arung Isyadi

Arung Isyadi

A full-time husband and dad who like to code for some money. Currently being entrusted as an Engineering Manager at an awesome team.

More from Medium

Supervisor Configuration in Laravel Homestead

Finding Function — PHP

How to Stop Spam Emails with reCAPTCHA, HTML & PHP

reCAPTCHA logo

Pros and cons of using Laravel with Vue js