phplaravellaravel-5.7

How to fix error Method Illuminate\Database\Query\Builder::attach does not exist. Attaching multiple items


I'm trying to attach "items model" to "events model.

Item Model:

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

Event Model

public function items()
{
   return $this->belongsToMany('App\Item', 'event_item');
}

User Model

public function items()
{
   return $this->hasMany('App\Item', 'user_id');
}

EventsController

public function store(Request $request)
{
  // Get user
  $user = $request->user();

  // Create event
  $event = Event::create(array_merge($request->all(), ['user_id' => $user->id]));

  // Attach items to event
  $user->items()->attach($event->id);

}

My user has multiple items. All user items need to be attached to events on store function. I get this error Method Illuminate\Database\Query\Builder::attach does not exist.


Solution

  • I was able to figure this out, easy mistake actually. I want to attach items to events but in my original question I have users attaching to items.

    Changed this:

    // Attach items to event
    $user->items()->attach($event->id);
    

    To this:

    // Attach items to event
    $event->items()->attach($user->items);
    

    Works as expected now.