Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

omar590's avatar

Passing several items to the callback of each() function

Hi I have a collection, I want to execute some action over each 10 of them

how to do so?

thanks!

0 likes
9 replies
omar590's avatar

thanks for replying

but I want every 10 items, not just one

I want for the first 10 items for instance to take number 1, and the next 10 items to take number 2

laracoft's avatar

@omar590

Ok, I did not understand that "... over each 10 of them".

Will this work? Use $key to work out your logic

$multiplied = $collection->map(function ($item, $key) {
    if ($key / 10)
    {
        return $item * 2;
    }
});
1 like
omar590's avatar

I will tell you the exact problem, you probably even have a better logic for it!

it's my first use to factories

and I have two tables, sections table that in one-to-many relation with users table

so how to create new users and assign each ten of them to an existing section

omar590's avatar

I'm still figuring out how to write it :'D

so it's basically the default

$factory->define(User::class, function (Faker $faker){

return [

    'name' => $faker->firstName.' '.$faker->lastName,
    'email' => $faker->unique()->safeEmail,
    'email_verified_at' => now(),
    'password' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    'remember_token' => Str::random(10),



];

});

I could elaborate more about the problem if you need any

and I'm sorry for being a novice

laracoft's avatar

@omar590

Use a seeder like here https://laravel.com/docs/8.x/seeding

Much easier to control your values.

    public function run()
    {
        for($i = 0; $i < 50; $++)
        {
            DB::table('users')->insert([
                'name' => Str::random(10),
                'email' => Str::random(10).'@gmail.com',
                'password' => Hash::make('password'),
                'section' => $i / 10;
            ]);
        }
    }
1 like

Please or to participate in this conversation.