We need to define the third table, which is the dynamic table.
Follow an example
Now, set the following scheme in the migration file.
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('product_id')->unsigned();
});
}
Define the relationships :
class Category extends Model
{
public function products(){
return $this->belongsToMany(Product::class);
}
}
The other
class Product extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
To create a product do
public function create(Request $request)
{
$product = new Product;
$product->name = 'God of War';
$product->price = 40;
$product->save();
$category = Category::find([3, 4]);
$product->categories()->attach($category);
return 'Success';
}
Thank you very much! :)
– Mateus Vieira