phplaravelforeacheach

Laravel each() method


I am trying to understand why the following is always returning false:

public function checkDate($transactions)
{
    $start = Carbon::now()->subMonth();
    $end = Carbon::now();

    $transactions->each(function ($transaction) use ($start, $end) {

        $date = Carbon::createFromFormat('Y-m-d', $transaction->date);

        if ($date->between($start, $end))
        {
            return true;
        }

        return false;
    });

    return false;
}

When I remove both the return false, then null is being displayed.

When I use a regular foreach, it works:

$start = Carbon::now()->subMonth();
$end = Carbon::now();

foreach($transactions as $transaction)
    {
        $date = Carbon::createFromFormat('Y-m-d', $transaction->date);

        if($date->between($start, $end))
        {
            return true;
        }

        return false;
    }

The thing what I don't understand is, when I do the following:

public function checkDate($transactions)
{
    $start = Carbon::now()->subMonth();
    $end = Carbon::now();

    $transactions->each(function ($transaction) use ($start, $end) {

        $date = Carbon::createFromFormat('Y-m-d', $transaction->date);

        if ($date->between($start, $end))
        {
            dd('test');
            return true;
        }

        return false;
    });

    return false;
}

Then "test" is being displayed.

Can someone explain as to why this is happening, since I don't understand it.


Solution

  • The each method doesn't stop iterating when true is returned. It does stop, however, when false is returned.

    If you would like to stop iterating through the items, you may return false from your callback:

    Collection Methods - each()

    Your method only returns false also.

    If you are trying to verify all transactions fall with a date range, then use the every method:

    // returns true if all transactions date are between start and end, otherwise returns false.
    return $transactions->every(function ($transaction) use ($start, $end) {
        $date = Carbon::createFromFormat('Y-m-d', $transaction->date);
    
        return $date->between($start, $end);
    });