I thought I was going quite well in developing my Laravel skills, but it seems I am stuck and can't find the solution online yet.
My project is set up in Laravel and Vue and I am trying to store a product with ingredients. The products are in the products table. The ingredients in the ingredients table. I succeeded in storing the product with a brand_id and later retrieve the brand (one-to-many), but I don't know how to do this for many-to-many: Ingredients to products.
Since I am working with Vue I have add JSON output that posts my data.
public function store()
{
$product = new Product();
$product->ean = request('ean');
$product->name = request('productName');
$product->brand_id = request('brandId');
$ingredients = request('ingredients');
$product->save();
}
As I explained above saving the product is going well. But now I need to do something with the $ingredients array, I've found lines like these:
$user->roles()->save($role);
So I think I have to do a foreach loop for all ingredients and within do this:
$product->ingredients()->save($ingredient);
What I fail to understand. This array will contain existing ingredients that are already stored, but also new ingredients that have to be added to the ingredients table. How to make this work?
So store new ingredients in it's table and also store the relation in the eloquent table. I might be close, I might be far off, anyone?