Laravel, what can each() function do?

Laravel, what can each() function do?

The each the 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.

<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
  
class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */
  
    use RegistersUsers;
  
    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
  
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    } 
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function showRegistrationForm()
    {
        return view('register');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
  
        $this->create($request->all());
  
        return redirect("dashboard");
    }
  
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
  
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}

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:

You can read about that here:

Collections also provide support for “higher-order messages”, which are short-cuts for performing common actions on collections.

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x