yigitozmen
yigitozmen

Reputation: 957

How to insert data to the additional field which is inside pivot table with laravel eloquent

My pivot table has additional field...

id  |  user_id   | language_id  | level
---------------------------------------

and my code:

User::find($this->userId)->languages()->attach(['language_id' => $lang_id, 'level' => $level]);

but the result is:

id  |  user_id   | language_id  | level
---------------------------------------
1       1            1            null
1       1            2            null

actually, second line's language_id must be first line's level...

how can i do it properly like this?

    id  |  user_id   | language_id  | level
     ---------------------------------------
     1       1            1            2

Upvotes: 0

Views: 66

Answers (2)

lukasgeiter
lukasgeiter

Reputation: 153010

attach() works a bit differently. The first parameter is the id or an instance of the other model and the second parameter are other pivot fields:

User::find($this->userId)->languages()->attach($lang_id, ['level' => $level]);

As @ceejayoz mentioned you also don't have withPivot() defined in your relationship. That means level won't be available in the result. Change that by adding withPivot() to both sides of the relation:

public function languages() {
    return $this->belongsToMany('Language')->withPivot('level');
}

Upvotes: 2

ceejayoz
ceejayoz

Reputation: 180065

Per the docs, you need to define the pivot table's data columns with the relationship.

public function languages() {
  return $this->belongsToMany('User')->withPivot('level');
}

Upvotes: 1

Related Questions