wim91's avatar

Why is an empty pivot table displayed when there is a many-to-many relationship?

Please help, I can't find information and understand why I can't get data on many-to-many connections.

I created 2 models and tables.

1. php artisan make:model Product -m

2. php artisan make:model Tags -m

Migrations

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name', 255);
            $table->timestamps();
        });
Schema::create('tags', function (Blueprint $table) {
            $table->id();
            $table->string('tag', 255);
            $table->timestamps();
        });

Next I created a pivot table

php artisan make:migration create_product_tags_table

Schema::create('product_tags', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('tag_id');
            $table->foreign('product_id')->references('id')->on('products');
            $table->foreign('tag_id')->references('id')->on('tags');
            $table->timestamps();
        });

Next I add methods to the models

//Model Product

protected $table = 'products';

public function tags()
    {
      return $this->belongsToMany(Tags::class);
    }

//Model Tags

protected $table = 'tags';

public function products()
    {
      return $this->belongsToMany(Product::class);
    }

Afterwards I fill the tables, and the pivot table too.

In the controller I try to get the data.

use App\Models\Product;

class MyController extends Controller
{
   public function view_data()
    {
		$data = Product::find(1)->tags();
		dd($data);
    }
}

I get an empty result... What's wrong?

0 likes
6 replies
Glukinho's avatar

First of all, your pivot table should be product_tag, not "...tags".

Second, you should retrieve data so:

Product::find(1)->tags()->get();
// or
Product::find(1)->tags;

->tags() retrieves only relation/query builder.

But I think the problem is pivot table name.

Update: model should be named Tag too, not Tags.

1 like
wim91's avatar

@Glukinho Can the model name influence the result if I explicitly set the table name in each model? protected $table = 'products'; and protected $table = 'tags';

Glukinho's avatar

@wim91 yes you can have your custom tables and models names, but it's always preferable to stick to conventions, they make life much easier.

1 like
wim91's avatar

@Glukinho (((( it's difficult, if you immediately set the name not according to the agreements, then nothing works, even if you explicitly specified all the parameters in the models(

1 like
wim91's avatar

I got it. Had to add parameters to make it work.

public function tags()
    {
     return $this->belongsToMany(Tags::class, 'product_tags', 'product_id', 'tag_id');
    }

Please or to participate in this conversation.