Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the each () method in the Laravel collection

Shulou Source: shulou.com Published: 2022-06-01 02:16:17 09月21日 Update

This article will explain in detail how to use each() method in Laravel collection. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.

each()

Each is a simple way to iterate over the entire collection. It accepts a callback with two parameters: the item it is iterating over and the key. Key is a zero-based index.

$collection->each(function ($item, $key) { info($item['user_id']);});

The above code simply records the user_id of each entry.

When iterating through the eloquent collection, you can access all column values as item properties. Here's how we iterate through all posts.

$posts = App\Post::all();$posts->each(function ($item, $key) { // Do something});

If false is returned in the callback, it stops iterating through the project.

$collection->each(function ($item, $key) { // Tasks if ($key == 1) { return false; }}); About "Laravel collection each() method how to use" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Tags: Iterations methods articles more good practical two code content parameters just properties posts articles being knowledge indexes projects references help Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Docker MariaDB Redmi Huawei