Thymeleaf
Thymeleaf

Reputation: 113

Best way to iterate throught returned models

I have a table named Drug basically when a drug is inserted it takes is_accepted 0 by default so it needs to be accepted by an administrator. All the drugs are shown on the website if their is_accepted value is 1

I have created a command DeleteunacceptedDrugs that will run every 12 hours.

This command will get all the drugs that their value is_accepted is 0 and check their waiting time (how long that they are in wait state)

public function handle()
    {
        $drugs =  Drug::where('is_accepted',0)->get();

        for($i=0;$i<count($drugs);$i++){
            if($drugs[$i]->getDuration() >= 12){
                $drugs[$i]->delete();
            }
        }

    }

This code works fine deletes all the drugs that their waiting time (current_date - created_at) is higher than 12 but the code looks ugly to me is there a way for a better iteration approach through drugs array

If you need it

 public function getDuration(){
    
            $start = Carbon::parse($this->created_at);
            $end = now();
            $hours = $end->diffInHours($start);
            return $hours;
        }

Upvotes: 0

Views: 30

Answers (1)

shaedrich
shaedrich

Reputation: 5735

You can do the diff directly in the query:

Drug::where('is_accepted',0)->whereRaw('HOUR(TIMEDIFF(created_at, NOW())) > 11')->delete();

Upvotes: 2

Related Questions