Northify
Northify

Reputation: 391

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.

Upvotes: 2

Views: 1410

Answers (3)

Northify
Northify

Reputation: 391

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.

Upvotes: 1

Affan Malik
Affan Malik

Reputation: 182

Your User model items function has to return a BelongsToMany relationship in order to use attach().

User Model:

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

Upvotes: 0

Blood
Blood

Reputation: 11

User Model:

 return $this->hasMany('App\Item', 'item_id');

Upvotes: 0

Related Questions