I have products
table with the following content:
+----+--------------+---------------+
| id | product_name | brand |
+----+--------------+---------------+
| 1 | Jacket | Zara |
| 2 | Jacket | Gucci |
| 3 | Towel | Zara |
| 4 | Towel | Pull and Bear |
| 5 | Towel | Levi's |
+----+--------------+---------------+
And shopping_list_items
with the following content:
+----+------------+--------------+----------+
| id | product_id | product_type | quantity |
+----+------------+--------------+----------+
| 1 | NULL | Jacket | 1 |
| 2 | NULL | Towel | 1 |
+----+------------+--------------+----------+
I set relationship Many-to-Many:
Product model
public function shopListType()
{
return $this->belongsToMany(Shopping_list_item::class, 'product_shopping_list_item', 'product_name', 'product_type');
}
Shopping_list_item model
public function productType()
{
return $this->belongsToMany(Product::class, 'product_shopping_list_item', 'product_type', 'product_name');
}
So when I add an item to shopping_list_items
table I want to save relation to products
table through product_shopping_list_item
.
Here is what I have in my Controller:
public function addShoppingListItem2(Request $request, Product $product)
{
$shop_list = $id;
$shopping_list_item = Shopping_list_item::firstorNew(['shopping_list_id' => $shop_list->id, 'product_type' => $request->product]);
$shopping_list_item->quantity = $request->quantity;
$shopping_list_item->product_type = $request->product;
$product->shopListType()->save($shopping_list_item);
}
But I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_type' cannot be null (SQL: insert into
shopping_list_items
(shopping_list_id
,product_type
,quantity
) values (13, ,1))
Why is product_type
null if I set it? If relationship set correctly?