Kataldo
Kataldo

Reputation: 37

Call to undefined method BelongsTo::attach()

Why isn't the relationship working?

I am trying to relate post and categories using laravel 5.2, mysql, migrations and seeders.

but I get an error:

Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::attach()

PostTableSeeder.php

public function run()
{
    factory(App\Post::class, 300)->create()->each(function (App\Post $post) {
        $post->category()->attach([
            rand(1, 5),
            rand(6, 14),
            rand(15, 20),

        ]);
    });
}

MODEL: Post.php

public function category()
{
  return $this->belongsTo(Category::class);
}

MODEL: Category.php

public function posts()
{
  return $this->belongsTo(Post::class);
}

Upvotes: 1

Views: 11477

Answers (1)

Salim Djerbouh
Salim Djerbouh

Reputation: 11064

Define a belongsToMany relationship in your model

public function category()
{
  return $this->belongsToMany(Category::class);
}

Don't forget to add an intermediate pivot table for Post and Category association

Since you don't RTFM, here's a full working example

PostTableSeeder.php

public function run()
{
    factory(App\Post::class, 300)->create()->each(function (App\Post $post) {
        $post->categories()->attach([
            rand(1, 5),
            rand(6, 14),
            rand(15, 20),
        ]);
    });
}

Post.php model

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

Category.php model

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

category_post table migration

Schema::create('category_post', function (Blueprint $table) {
    $table->unsignedBigInteger('post_id');
    $table->unsignedBigInteger('category_id');
});

Hope this helps :)

Upvotes: 4

Related Questions