Luka

Update a one-to-many relation with possibly additional data attached

Posted 11 months ago by Luka

I'm currently trying to update a one-to-many relation in Eloquent. I have got an Event Model and the Event can have Many Event Dates.

class Event extends Model
{

protected $fillable = ['event_name', 'event_description'];

public function eventdates()
{
    return $this->hasMany('App\EventDates');
}

}

  class EventDates extends Model
  {

  protected $fillable = [ 'event_date','event_starttime','event_endtime','event_id'];

  protected $dates = ['event_date'];

  public function event()
  {
     return $this->belongsTo('App\Event', 'event_id');
  }
 }

  class Image extends Model
 {
   public $fillable = ['image_name'];

   public function events()
   {
      return $this->hasOne('App\Event','event_image_id');
   }
 }

The Problem is now the update.

I have done the following in my Controller:

  public function update(Request $request, $id)
  {
   
    $event = Event::findOrFail($id);
    $input = $request->all();
    $event->update($input);
    
    $rows =  $request->input('event_date'); 
    
    for($i=0; $i <count($rows);$i++)
    {
        $eventDates = [
          //  'event_id' => $event->id,
            'event_date' =>   \Carbon\Carbon::createFromFormat('d-m-Y', $request->event_date[$i]),
            'event_starttime' => $request->event_starttime[$i],
            'event_endtime' => $request->event_endtime[$i]   
        ];
        
         $event->eventdates()->update($eventDates);
    }

This works fine, when you have a date in the database and you update that. But, my form offers the option to add additional date fields dynamic. It could be that you entered just 1 date originally, but now you realise the event goes over 2 days so you have to add a date, which means you have to insert instead of update. It might also happen that you have to update the first date + insert an additional date.

I found updateOrCreate and tried that but it seems to Create 2 new records, when I update the existing record and add 1 date. I obviously got a logical error here, but how to achieve that?

Please sign in or create an account to participate in this conversation.