I'm building an app based off of the Laravel bootcamp app and I'm trying to add additional filtering based off of the with statement.
Some probably obvious things:
- each user has a city
- each call has a user referenced by user_id
public function index()
{
$user = auth()->user();
$city = $user->city;
return Inertia::render('Calls/Index', [
'calls' => Call::with('user:id,name,city,state,email')->latest()->get(),
]);
}
I need to only get calls whose user has the same location as them. Is there something obvious I'm missing?
CodePudding user response:
When retrieving model records, you may wish to limit your results based on the existence of a relationship, there is where you can use whereHas
I presume you have a relation in your Interia Model refer to User model:
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
now you can make you code like this:
return Inertia::render('Calls/Index', [
'calls' => Call::with('user:id,name,city,state,email')->whereHas('user',function ($q) use ($city) {
$q->where('city',$city);
})->latest()->get(),
]);