Home » Php » How to use break or continue with Laravel Eloquent Collection's each method?

How to use break or continue with Laravel Eloquent Collection's each method?

Posted by: admin November 29, 2017 Leave a comment

Questions:

How to use break or continue with Laravel Eloquent Collection’s each method.
My code is this:

$objectives->each(function($objective) {
        Collection::make($objective)->each(function($action) {
            Collection::make($action)->each(function($success_indicator) {
                Collection::make($success_indicator)->each(function($success_indicator) {
                    echo 'hi';
                    continue;
                });
            });
        });
    });
Answers:

To continue, just return out of the inner function. To break, well..

If you’re using Laravel 5.1+, you can return false to break the loop:

$objectives->each(function($objective) {
    collect($objective)->each(function($action) {
        collect($action)->each(function($success_indicator) {
            collect($success_indicator)->each(function($success_indicator) {
                if ($condition) return false;
            });
        });
    });
});

For older version of Laravel, use a regular foreach loop:

$objectives->each(function($objective) {
    foreach ($objective as $action) {
        foreach ($action as $success_indicators) {
            foreach ($success_indicators as $success_indicator) {
                echo 'hi';
                break;
            }
        }
    }
});

Questions:
Answers:

We can return true/false true for continue, false for break

Continue:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return true;
            }
            echo $item;
});

Output:
1 3 4

Break:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return false;
            }
            echo $item;
});

Output:
1

Leave a Reply

Your email address will not be published. Required fields are marked *