Skip to content
Advertisement

Store product multiple colors to the database Laravel

I have a product table which has price, name, stock etc. and color_products table which has color_id, product_id. I want to store a product to the database with selected colors so far I’m getting an error Invalid argument supplied for foreach(). How can I fix this?

Controller

 $formInput=$request->all();   //If I do dd($formInput) I see all data

    $product = product::create(array_merge($formInput, [
        'user_id' => Auth::user()->id
    ]));
   
 // Insert color to the database

    $store_color = [];
    $colors = $request->color_id;

    foreach ($colors as $color) {
        $ouzColor = $color->save;
        $store_color[] = [
            'product_id' => $product->id,
            'color_id' =>  $ouzColor
        ];
    }
        ColorProduct::insert($store_color);

Blade file

  <select multiple name="color_id" id="color">
     <option value=""> --Select Colors -- </option>
         @foreach($colors as $color)
           <option value="{{ $color->id }}" >{{$color->name}}</option>
         @endforeach
  </select>

Advertisement

Answer

try to rename your select field to be something like that <select multiple name="color_id[]" id="color">

let’s take it a step by a step.

$product = Product::create([
            'field 1' => $request->field1,
            'filed 2' => $request->field2,
            'user_id' => Auth::user()->id,
        ]);
        $store_color = [];
        foreach ($request->color_id as $index=>$color) {
        $store_color[$index] = [
            'product_id' => $product->id,
            'color_id' =>  $color,
        ];
    }
        ColorProduct::insert($store_color);

of course, you need to change filed1 and 2 with its real names and value

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