-1

I have a tables peoples countries and a pivot table country_people. The pivot tables has got attributes countries_id peoples_id number. I am able to get the foreign keys into the pivot table but i can't insert into number. How do i do this ?

People model

 public function countries()
    {
        return $this->belongsToMany('App\Country')->withPivot('number')
        ->withTimestamps();
    }

Country model

public function peoples()
    {
        return $this->belongsToMany('App\People')->withPivot('number')
        ->withTimestamps();
    }

Controller

   $people = new People(array(
        'quantity' => $request->get('quantity'),

    ));

    $people->save();
    $order->countries()->sync($request->get('id')->attach('quantity'));

2 Answers2

1

It looks like you're combining update methods. Check out https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships for more details.

In your case, try:

$order->countries()->attach($request->get('id'), ['number' =>
$peoples['quantity']);

If you want to sync, instead of attach, use:

$order->countries()->sync([$request->get('id') => ['number' =>
$peoples['quantity']]);
Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31
Stretsh
  • 193
  • 1
  • 12
0

If you want to attach additional columns to the pivot table, you can pass it in through as array. For example:

$id = intval($request->get('id'));        
$order->countries()->sync( $id => ['number' => $quantity]);  //assuming you have saved the value of number in quantity

Take a look at https://laravel.com/docs/5.5/eloquent-relationships under syncing associations for more details.

Also, keep in mind that using sync will remove any of the previous relationships if they are not specified in the array. Use syncWithoutDetaching if you don't want this to happen.

pseudoanime
  • 1,547
  • 12
  • 19