Ad

Laravel Many-To-Many Relationship With Multiple Functions

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?

Ad

Answer

While looping the ingredients, look into the firstOrNew() method:

foreach($request->input("ingredients") AS $ingredient){
  $ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
  // Note: assumed name for column that matches `$ingredient` from array, adjust as needed.
}

While in that loop, attach() your $ingredient to your new $product. Your code should look like this when fully implemented:

$product = new Product();
...
$product->save();

foreach($request->input("ingredients") AS $ingredient){
  $ingredient = Ingredient::firstOrNew(["name" => $ingredient]);
  $product->ingredients()->attach($ingredient->id); 
}

attach() will associate this new or existing $ingredient with the new $product by adding a record to the pivot between Product and Ingredient. The reason you can't use $product->ingredients()->save($ingredient); is that this is a many-to-many, which requires attach(). $model->relationship()->save(); is used for a one-to-many.

Full documentation on the creation methods can be found here: https://laravel.com/docs/5.8/eloquent#other-creation-methods

Ad
source: stackoverflow.com
Ad