Generate Collections on the Fly with Laravel's times Method
- Published on 23 December, 2024
- Words: 42
Need to create a collection with calculated values? Laravel's times method lets you generate collections dynamically!
#Basic Usage
Here's the simplest way to use times:
$collection = Collection::times(10, function (int $number) {
return $number * 9;
});
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
#Real-World Example
Here's how you might use it in a date slot generator:
class AppointmentSlotGenerator
{
public function generateDailySlots(
string $startTime = '09:00',
int $slotCount = 8,
int $intervalMinutes = 60
) {
return Collection::times($slotCount, function (int $index) use ($startTime, $intervalMinutes) {
$time = Carbon::parse($startTime)
->addMinutes(($index) * $intervalMinutes);
return [
'slot_id' => $index + 1,
'start_time' => $time->format('H:i'),
'end_time' => $time->addMinutes($intervalMinutes)->format('H:i'),
'is_available' => true
];
});
}
}
// Usage
$generator = new AppointmentSlotGenerator();
$slots = $generator->generateDailySlots('10:00', 6, 30);
$slots->each(function ($slot) {
$this->info("Slot {$slot['slot_id']}: {$slot['start_time']} - {$slot['end_time']}");
});
The times method is perfect for generating sequences, creating test data, or any scenario where you need calculated values in a collection.
Antonio Jenaro
Web Developer
Source: Harris Raftopoulos
Start the conversation
Become a member of Antonio Jenaro to start commenting.
Sign up nowAlready a member? Sign in