irankhosravi
5 months ago
57
17
Laravel

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into `category_product`

Posted 5 months ago by irankhosravi

Look at my codes

public function store(ProductRequest $request)
{
    $product = new Product();
    $product->user_id = auth()->user()->id;
    $product->title = $request->title;
    $product->body = $request->body;
    $product->price = $request->price;
    $product->categories()->attach($request->category);
    $image = $request->image;
    $filename = $image->getClientOriginalName();
    $image->move(public_path('images/products'), $filename);
    $product->image = $image;

    return redirect()->route('products.index');
}

Product.php

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

I get this error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_id' cannot be null (SQL: insert into category_product (category_id, product_id) values (1, ?), (2, ?))

But I select a category of product already.

Please sign in or create an account to participate in this conversation.