Sid Heart Sid Heart - 3 months ago 16
MySQL Question

how to attach many to many relationship in laravel

i have 2 table 1st products belongsToMany Colors and 2nd Colors belongsToMany products

i maked my table like this


Product Table

Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('image');
$table->string('stock');
$table->string('title');
$table->string('slug')->unique();
$table->string('gender');
$table->text('description');
$table->integer('price');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');

$table->dateTime('published_at');
});


and Color Table with relationship

Schema::create('colors', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});

Schema::create('color_product', function (Blueprint $table) {
$table->integer('color_id')->unsigned()->index();
$table->foreign('color_id')->references('id')->on('colors')
->onDelete('restrict')
->onUpdate('restrict');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')
->onDelete('restrict')
->onUpdate('restrict');
$table->timestamps();
});


i am trying to add more color in in 1 product like this

public function addproductdetailspost(Request $request, $product){

$product = product::where('slug', $product)->firstorfail();
$color = color::where('name', $request->color)->firstOrCreate();
$color->name = $request->color;
$color->save();
$product_id = $product->id;
$color_id = $color->id;
$product->colors()->attach($product_id);
return Redirect::back()->with('status', 'Post Success');
}


its not working Getting Error

Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::firstOrNew(), 0 passed in C:\xampp\htdocs\swimwear2\app\Http\Controllers\AdminController.php on line 109 and at least 1 expected


Help me!!

Answer Source

It's the wrong direction.

$color->products()->attach($product_id);