There is a function like this in User model in Laravel
public function isOldUser(): bool
{
return Cache::tags(['is-user-old'])->remember('user-' . $this->id . '-is-old', 60 * 60 * 24, function () {
$hasOldTreatmentPlan = $this->treatmentplans->contains(function ($treatmentplan) {
return $treatmentplan->created_at <= Carbon::today()->subMonths(3);
});
$hasOldVisit = $this->bookings->contains(function ($booking) {
return $booking->booking_at <= Carbon::today()->subMonths(3) &&
$booking->visit_type == BookingVisitTypeEnum::IN_PERSON->value &&
$booking->visit?->exists() &&
$booking->type == BookingTypeEnums::VISIT->value;
});
return $hasOldVisit && $hasOldTreatmentPlan;
});
}
I need to have a scope for this
public function scopeIsOldUserFilter($query, bool $criteria = true)
{
}
I have tried but didn’t work, like this
public function scopeIsOldUserFilter($query, bool $criteria = true)
{
$query->where(function ($query) use ($criteria) {
return $this->isOldUser() == $criteria;
});
}
How to add scope which filters of a user is old or not.
A scope should only add constraints to the query, since the models have not yet been retrieved from the database.
The following is an example of how it could look like. It probably won’t work immediately, since I’m not sure of how your relations are set up.
public function scopeIsOldUserFilter($query, bool $criteria = true)
{
if ($criteria) {
$query
->whereRelation('treatmentplans', 'created_at', '<=', Carbon::today()->subMonths(3))
->whereHas('bookings', function ($query) {
$query
->where('booking_at', '<=', Carbon::today()->subMonths(3))
->where('visit_type', BookingVisitTypeEnum::IN_PERSON->value)
->whereHas('visit')
->where('type', BookingTypeEnums::VISIT->value);
});
} else {
$query
->whereRelation('treatmentplans', 'created_at', '>', Carbon::today()->subMonths(3))
->orWhereDoesntHave('bookings', function ($query) {
$query
->where('booking_at', '<=', Carbon::today()->subMonths(3))
->where('visit_type', BookingVisitTypeEnum::IN_PERSON->value)
->whereHas('visit')
->where('type', BookingTypeEnums::VISIT->value);
});
}
}
4