Nasif Md. Tanjim Nasif Md. Tanjim - 3 months ago 49
PHP Question

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.
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;
});
});
});
});

Answer

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;
            }
        }
    }
});
Comments