I have no specific work to do, just want to know what each() can do.
I have googled, and saw this post: https://github.com/laravel/framework/issues/1380
It says
each is there to perform some operations on all items, that's all there is to it and that is what each is already doing.
What are the operations?
The each method will iterate over items in the collection and allow you to execute code on each item. The difference between each and map is that while each simply iterates through the values, map replaces the value with whatever is returned in the callback. The documentation for each is found here. If you want to look at the source code.
The each method iterates over the items in the collection and passes each item to a callback. If you would like to stop iterating through the items, you may return false from your callback.
$users->each(function($user, $key) {
$user->update(['last_login' => Carbon::now()]);
});
The "some operations" you are inquiring about is the callback. In this case the callback/operation is:
function($user, $key) {
$user->update(['last_login' => Carbon::now()]);
}
This will update all the users in the collection's last login to the current time. Additionally, if you have a method on the User model named updateLogin
class User extends Model
{
public function updateLogin()
{
$this->update(['last_login' => Carbon::now()]);
}
}
You can actually just do the following with a collection of $users:
$users->each->updateLogin();
You can read about that here:
Collections also provide support for "higher order messages", which are short-cuts for performing common actions on collections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With