Level 122
you dont need to do either query inside the loop as neither contains any variable data?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
how can I refactor the below code and optimize the query of the Database?
$times = SampleTime::all();
$now = Carbon::now()->timezone('My/timezone')->format('H:i');
$times->each(function ($time) use ($now) {
$diff = Carbon::parse($time->time)->diffInMinutes($now);
$this->alert($diff);
if ($diff <= 15) {
$roleIds = Role::select('id')
->whereJsonContains('permissions', ['sections/sampler'])
->pluck('id')
->toArray();
if (filled($roleIds)) {
$samplers = Admin::roleIds($roleIds)->get();
}
foreach ($samplers as $sampler) {
// send sms
$this->info($sampler->first_name);
}
}
});
I Want to refactor the code and optimize the query to the database
Please or to participate in this conversation.