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?