https://laravel.com/docs/8.x/collections#the-enumerable-contract
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
Every item will be strtoupper(...)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi I have a collection, I want to execute some action over each 10 of them
how to do so?
thanks!
https://laravel.com/docs/8.x/collections#the-enumerable-contract
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})
Every item will be strtoupper(...)
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
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;
}
});
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 show your factory code please, why not use a seeder?
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
Where is the section field?
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;
]);
}
}
Please or to participate in this conversation.