I'm trying to figure out a better way to query my data, since it's taking ~5+ seconds to get the results.
I have the following models:
Lead
public function textHistory()
{
return $this->hasMany(LeadTextHistory::class)->orderByDesc('created_at');
}
public function latestText()
{
return $this->hasOne(LeadTextHistory::class)->ofMany('created_at', 'max');
}
public function scopeUnresponded($query)
{
return $query->whereHas('latestText', function ($query) {
$query->where('type', 'Incoming');
});
}
LeadTextHistory
public function lead()
{
return $this->belongsTo(Lead::class);
}
My controller contains:
public function index()
{
$user = auth()->user();
$query = Lead::query();
// only show leads assigned to current user unless they are admin
if (! $user->hasRole('admin')) {
$query->where('user_id', $user->id);
}
$query->whereHas('latestText')
->with([
'user',
'latestText',
'latestText.user',
'latestText.reviews',
]);
if (request()->has('search') && request()->input('search') != '') {
$query->whereHas('latestText', function ($query) {
$query->where('text', 'like', '%'.request()->input('search').'%');
});
}
if (request()->has('unresponded') && request()->input('unresponded') == 'true') {
$query->unresponded();
}
if (request()->wantsJson()) {
if ($query->count() > 0) {
// return an array of totalTexts and leads
return [
'totalLeads' => $query->count(),
'leads' => $query->paginate(100),
];
}
}
$leads = $query->paginate(100);
return Inertia::render('Leads/Texts', [
'leads' => $leads,
'totalLeads' => $leads->total(),
'filters' => request()->all(['status', 'unresponded', 'unreviewed']),
]);
}
The problem occurs when using $query->unresponded();
Can someone help point me into the right direction on how to speed up this query?