0

i have pivot table like this

enter image description here

this is my Users model

 public function getHousing()
{
    return $this->belongsToMany(Housing::class, 'user_housing', 'user_id', 'housing_id')->withPivot('primary');
}

this is my Housing model

   public function getUser()
{
    return $this->belongsToMany(Users::class, 'user_housing', 'housing_id', 'user_id')->withPivot('primary');
}

i want to save primary with 1, this is my controller

     $getData = $this->crud->show($id);
    if (!$getData) {
        return redirect()->route('admin.' . $this->route . '.index');
    }

    $data = $this->validate($this->request, [
        'housing_group_id' => 'required',
        'housing_id' => 'required',
        'primary'   => 'required',
    ]);

    $getData->housing_id = $getData->getHousing()->pluck('id')->toArray();


    $getData->getHousing()->sync($this->request->get('housing_id'), ['primary' => 1]);


    $id = $getData->id;

i already add array fill primary 1, but i have error like this

SQLSTATE[HY000]: General error: 1364 Field 'primary' doesn't have a default value 

how to save additional field in pivot table laravel ? thanks

Bian
  • 95
  • 2
  • 10

1 Answers1

0

in sync with additional column in pivot table, you should pass an associative array for each id with column name as key and field value as value

$elements_array[$this->request->get('housing_id')]=['primary' => 1]
$getData->getHousing()->sync(elements_array);

if you have more than an 'id' to sync ... you must repeat the first step for each id.

check this: https://stackoverflow.com/a/27230803/10573560

OMR
  • 11,736
  • 5
  • 20
  • 35