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

usmanlatif306's avatar

How to save single date from dates array in database in laravel

I have an array of dates which may has same date but always different time. I want to save single entry for similar date in "dates" table and times of similar date in separate "times" table with having "date_id" of its respective date.. Can anyone please help me to achieve this in laravel.

The array of dates is like this.

[ "Wed Dec 01 2021 21:00:00 GMT+0500", "Wed Dec 01 2021 22:00:00 GMT+0500", "Wed Dec 01 2021 23:00:00 GMT+0500", "Wed Dec 01 2021 20:00:00 GMT+0500", "Thu Dec 02 2021 12:00:00 GMT+0500", "Thu Dec 02 2021 14:00:00 GMT+0500", "Thu Dec 02 2021 22:00:00 GMT+0500", "Fri Dec 03 2021 22:00:00 GMT+0500", "Fri Dec 03 2021 23:00:00 GMT+0500", "Sat Dec 04 2021 16:00:00 GMT+0500", "Sat Dec 04 2021 19:00:00 GMT+0500", "Sat Dec 04 2021 22:00:00 GMT+0500", "Sun Dec 05 2021 16:00:00 GMT+0500" ]

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Group the dates

$grouped = collect($array)->groupBy(function ($item, $key) {
    return Carbon::parse($item)->toDateString();
});
//now you can foreach nested
foreach ($grouped as $date => $items) {
    //create the date record here using $date
    $model = Date::create(['date' = > $date]);
   $inserts = [];
    foreach ($items as $timestamp) {
         //insert timestamps with date_id = $id from above
        $inserts[] = ['time' => Carbon::parse($timestamp)->toTimeString(), 'date_id' => $model->id];
     }
     Time::insert($inserts);
}

The second loop is a single insert, to avoid alot of database queries :)

1 like
usmanlatif306's avatar

@Sinnbeck Thanks you so much sir. It is exactly the same as I want. Thanks again sir from my heart for solving my problem.

Please or to participate in this conversation.