0
votes

I have this 3 table:

stations (id,station_name)
products (id,product_name)

pivot table

product_station (station_id,product_id, tank_volum)

enter image description here

Station Model

public function products(){
        return $this->belongsToMany(Product::class)
            ->withTimestamps()
            ->withPivot('tank_volume');
    }

Product Model

  public function stations(){
        
   return $this->belongsToMany(Station::class);
    }

I'm trying to create a station with many products and every product have it's tank volume but i can't save the tank volume value to database:

product_station table

enter image description here

this is my controller:

public function store(StationsRequest $request)
    {

//        dd($request);

        $input = $request->all();

        if($file = $request->file('photo_id')) {

            $name = time() . $file->getClientOriginalName();

            $file->move('images', $name);

            $photo = Photo::create(['file'=>$name]);

            $input['photo_id'] = $photo->id;

        }

       $station = Station::create($input);

       $station->products()->sync($request->products , false);

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

enter image description here

Q: How can i Save Tank volume inside product_station table "pivot table" ?

1
that isn't a pivot table it is a bridge tablenbk
I don't see tank_volume variable in your code.Tpojka
yes i know i tried a lot but it didn't workshaher11
I mean, is tank_volume some predefined value? There is no tank_volume in store method. How do you get value of tank_volume? Is it from request, where do you find it?Tpojka
no it is not predefined the process to create is: add station details, select product and add tank volume to this selected product . . but i don't know how to save the tank volume with author data in the same pivot tableshaher11

1 Answers

0
votes

if you want to sync() related extra fields :

$product_ids = [];
foreach ($station->products as $product) {
    //collect all inserted record IDs
    $product_ids[$product->id] = ['tank_volume' => 'tank_volume_value'];  
}
//if you want to pass new id from new query
//$product_ids['new_created_product->id'] = ['tank_volume' => 'tank_volume_value'];

then

$station->products()->sync($product_ids);

in this case, better use attach() :

$station = Station::create(['fields']);
$station->products()->attach([$product->id => ['tank_volume'=>'value']]);