phplaravele-commerceproductvoyager

Store related items with many-to-many relationship Laravel


I'm overriding voyager admin panel & trying to store multiple related items in add new product form. My view is

<div class="form-group col-md-8">
   <label class="control-label">Related Products</label>
   <select class="form-control chosen-select">
    @foreach($products as $product)
     <option class="form-control" value="{{$product->id}}" name="related_id[]"> {{$product->name}} </option>
    @endforeach
   </select>
 </div>

Product Model

public function related() {
        return $this->belongsToMany('App\Product', 'related_products', 'product_id', 'related_id');
    }

RelatedProduct Model

class RelatedProduct extends Model
{
    //
    protected $table = 'related_products';
    protected $fillable = ['product_id', 'related_id'];

    public function products() {
        return $this->belongsTo('App\Product', 'related_products', 'product_id', 'related_id');
    }
}

Product Controller

if($data->save()) {
            $productId = $data->id;
            $products = [];
            for ($i=0; $i < $request->related_id; $i++) { 
            
                array_push($products, [
                    'product_id' => $productId,
                    'related_id' => $request->related_id[$i]
                ]);
            }
            

            // Related product pivot table bulk insertion
            RelatedProduct::insert($products);
            
            // response stuff
            return response()->json([
                'success' => true,
                'last_insert_id' => $data->id,
                'related_id'    =>  $request->related_id,
        ], 200);

        }

Everything is working fine but related_id is going null.


Solution

  • Try changing loop.Since you haven't mentioned count of related_id.that might be the reason.

      for ($i=0; $i < count((array)$request->related_id); $i++) {
    
                array_push($products, [
                    'product_id' => $productId,
                    'related_id' => $request->related_id[$i]
                ]);
            }
    

    Updated also you have error in select

     <select class="form-control chosen-select" name="related_id[]">
        @foreach($products as $product)
         <option class="form-control" value="{{$product->id}}" > {{$product->name}} </option>
        @endforeach
       </select>