Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pouyabh's avatar

how can i code refactor and optimize laravel query

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

0 likes
2 replies
Snapey's avatar

you dont need to do either query inside the loop as neither contains any variable data?

Please or to participate in this conversation.