Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel "undefined method Illuminate\Database\Query\Builder::attach()"

I'm trying to associate related models during database seeding in Laravel 4. According to the documentation here, I can do it like this:

$user->roles()->attach(1);

So, in my database seed I'm running:

$package = Package::create([
    'name' => $faker->word,
    'summary' => $faker->sentence,
    'base_price' => $faker->randomFloat(2, 200, 10000)
]);

// Attach 1-5 randomly selected items to this package
foreach(range(1, 5) as $index)
{
    $randomItem = Item::orderBy(DB::raw('RAND()'))->first();
    $package->items()->attach($randomItem->id);
}

The packages items have already been seeded at this point, and they seed without problems. The above code gives this from Artisan though:

[BadMethodCallException]                                              
Call to undefined method Illuminate\Database\Query\Builder::attach()

Someone here seems to think that the attach() method doesn't actually exist and the docs are wrong, but I find that hard to believe.

TL;DR What is the correct way to create many-to-many relationships in Eloquent?

like image 584
glasstree Avatar asked Mar 19 '14 02:03

glasstree


1 Answers

The function items() in your Package model has to return a BelongsToMany relationship in order to use attach().

public function items() {
  return $this->belongsToMany('Item');
}
like image 88
TonyArra Avatar answered Oct 19 '22 22:10

TonyArra