Home > Back-end >  What is the proper way to do for each where in laravel
What is the proper way to do for each where in laravel

Time:07-16

I have these 2 functions below. I want to change $report->rate to count of results. So total rows from this query foreach($campaign->reports->where('status', 2) so if there is 10 results that's true it will be $total_cap = $total_cap 10;

public static function checkTotalCap(Campaign $campaign)
{
    $total_cap = 0;
    foreach($campaign->reports->where('status', 2) as $report)
    {
        $total_cap = $total_cap   $report->rate;
    }

    if($campaign->cap <= $total_cap)
        return true;

    return false;
}

public static function checkDailyCap(Campaign $campaign)
{
    $daily_cap = 0;
    foreach($campaign->reports->where('status', 2) as $report)
    {
        if($report->created_at->isToday())
        {
            $daily_cap = $daily_cap   $report->rate;
        }
    }

    if($campaign->daily_cap <= $daily_cap)
        return true;

    return false;
}

This is how its used

if($campaign->cap !== 0)
        {
            // Check if total cap or daily cap reached
            if($this->checkTotalCap($campaign) || $this->checkDailyCap($campaign))
            {
                $campaign->active = 'no';
                $campaign->save();
                return "The campaign has reached its cap.";
            }
        }

CodePudding user response:

You can do this pretty simply

$reports = $campaign->reports()->where('status', 2)->whereDate('created_at', now())->get();

foreach($reports as $report)
{
   $daily_cap = $daily_cap   $report->rate;
}

Write separate query with conditions and simply loop it.

CodePudding user response:

You can try this to filter the reports with status == 2 and:

$reports = $campaign->reports()->where('status', 2)->get();

foreach($reports as $report) {
    //TODO
}

CodePudding user response:

You don't even need the foreach() loops at all here:

public static function checkTotalCap(Campaign $campaign) {
  return $campaign->reports()->where('status', 2)->count() > $campaign->cap;
  // OR
  // $campaign->cap <= return $campaign->reports()->where('status', 2)->count();
}

public static function checkDailyCap(Campaign $campaign) {
  return $campaign->reports()->where('created_at', Carbon::today())->where('status', 2)->count() > $campaign->daily_cap;
  // OR
  // return $campaign->daily_cap <= $campaign->reports()->where('created_at', Carbon::today())->where('status', 2)->count();
}

Use SQL-level queries to get the SUM of each Report's rate column, and compare against $campaign->cap.

  • Related