lundi 2 mars 2020

How can I Insert multi inputs using pivot table in laravel?

I have 3 tables:

  • stations (id,station_name)
  • products (id,product_name)
  • product_station (station_id,product_id)

enter image description here

I already have inserted stations and products and i want to insert multi products to the selected station using Pivot table

ProductStationController

public function edit($id)
    {
        $station = Station::findOrFail($id);

        $products = Product::pluck('product_name','id')->all();

        return view('admin.product_station.edit',compact('station','products'));
    }

enter image description here

and I add this code to insert the multi products to the selected station But it does not work So i need help plz :)

public function update(Request $request, $id) { $station = Station::findOrFail($id);

   $products = explode(",", $request->get('products'));
   $product_ids1 = [];
   $product_ids2 = [];
   $product_ids3 = [];
   $product_ids4 = [];

   foreach ($products as $product) {
     $product_db = Product::where('product_name', trim($product))->Create(['product_name' =>
     trim($product)]);

     $product_ids1[] = $product_db->id;
     $product_ids2[] = $product_db->id;
     $product_ids3[] = $product_db->id;
     $product_ids4[] = $product_db->id;
        }

        $station->products()->syncWithoutDetaching($product_ids1);
        $station->products()->syncWithoutDetaching($product_ids2);
        $station->products()->syncWithoutDetaching($product_ids3);
        $station->products()->syncWithoutDetaching($product_ids4);

        $station->update($request->all());

        return redirect('/admin/stations');
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire