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

skoobi's avatar
Level 13

Elequent checking for duplications

Hi. Im trying to sync reservations from a table in the database into an events/posts table.

What it needs to be able to do is create a post in the post table, then use the post id in the events table, but get the information from the reservation table.

The code below works but if i run it twice it will duplicate the data.

How do i do it so it looks for the reservation id from the post_id in post or events reservation_id. Hope this makes sense.

public function sync()
    {
        // Create the bookings
        $reservations = Reservation::all();
        $events = Event::all();

        foreach($reservations as $reservation) { 
            
            // Create a new post for the event
            $post = new Post(array(
                'post_author' => 8,
                'post_date' => date('Y-m-d'),
                'post_date_gmt' => date('Y-m-d'),
                'post_content' => 'Reserved Booking',
                'post_title' => 'Reserved Booking',
                'post_excerpt' => 'Reserved Booking',
                'post_status' => 'publish',
                'to_ping' => '',
                'pinged' => '',
                'post_content_filtered' => '',
                'comment_status' => 'closed',
                'ping_status' => 'closed',
                'post_name' => 'reserved-' . $reservation->id,
                'post_type' => 'event',
                'post_modified' => date('Y-m-d G:i:s'),
                'post_modified_gmt' => date('Y-m-d G:i:s'),
            ));
            $post->save();

            // Create the event from the reservation 
            $event = new Event(array(
                'post_id' => $post->id,
                'StartDate' => date('Y-m-d', strtotime($reservation->check_in)),
                'EndDate' => date('Y-m-d', strtotime($reservation->check_in)),
                'StartTime' => date('G:i:00', strtotime($reservation->start_hour)),
                'FinishTime' => date('G:i:00', strtotime($reservation->end_hour)),
                'event_occurrence' => 0,
                'reservation' => $reservation->id,
            ));      
            $event->save();             
        }
        
        return redirect(action('HomeController@index'))
                ->with('status', 'All entries have been added to the database!');
    }

Any help or information would be greatful.

Many Thanks

0 likes
0 replies

Please or to participate in this conversation.