Skip to content
Advertisement

store data into pivot table laravel 8

i have manytomany relation ship between categroy and product category model

class Attribute extends Model implements Auditable
{
    use HasFactory, AuditableTrait;
    protected $fillable = ['category','sub_categ'];
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }

}

product model

class Product extends Model implements Auditable
{
    use HasFactory, AuditableTrait;
    protected $table = 'products';
    protected $fillable = ['name','price','description', 'details'];
    public function products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class);
    }
}

the pivot table

Schema::create('attributes_products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('product_id')->constrained('products')->onUpdata('cascade')->onDelete('cascade');
            $table->foreignId('attribute_id')->constrained('attributes')->onUpdata('cascade')->onDelete('cascade');
        });

what should i do after this i did not undrestant how attach will work in pivot table and return it with the product as json response ?

edit

this is the schema i am working on enter image description here

i want to give each product it’s own category and this is my product controller store function

 public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'price' => 'required|numeric',
            'description' => 'required',
            'details' => 'required',
            'stocks' => 'required|numeric',
            //'discounts' => 'required|numeric'
        ]);

        $product = Product::create($request->only('name','price','description', 'details'));
        
        $product->stocks()->create([
            'quantity' => $request->stocks,
            'product_id' => $product->id
        ]);

        $product->discounts()->create([
            //'discount' => $request->discounts,
            'product_id' => $product->id
        ]);

        if($request->hasFile('images'))
        {
            foreach( $request->file('images') as $file)
            {
                $file->store('public/products');
                $product->images()->create([
                    'product_id' => $product->id,
                    'file_path'  => $file->hashName()
                ]);
            }
        }

        $product->categories()->sync([
            'product_id' => $product->id,
            'attribute_id'=> 1
        ]);
    }

Advertisement

Answer

In your product model check your relation.

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

Also usually the pivot table needs to have only 2 Ids. So in your case only 2 columns: product_id & category_id.

Your table name by convention should be category_product, otherwise, you should specify it on the second parameter on the relationship.

  • Fix this too, you got a typo on update:

    $table->foreignId('attribute_id')->constrained('attributes')->onUpdate('cascade')->onDelete('cascade');

  • And finally to attach:

    $product = Product::find(1);

    $product->categories()->attach($categoryId);

All is explained very well on documentation too: https://laravel.com/docs/8.x/eloquent-relationships

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement