0

I am a newbie at Laravel framework and trying to work me in. I already understand how to generate N:M relationships and handle them inside the models. Now I am asking you how to fill an additional field inside the many to many tables?

For example:

  • Table Foo

  • Table User_Foo

    • user_id
    • foo_id
    • is_owner (bool)
  • Table User

Now I want to declare which of the foo users is the real owner. In my opinion, the N:M Table has stored this information an not the Foo itself. So how is it possible to declare those additional fields inside of my Foo and User model?

Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
user1410569
  • 13
  • 1
  • 7

2 Answers2

0

Retrieve additional fields you can with withPivot() method

return $this->belongsToMany('App\User')->withPivot('is_owner');

Fill you can with sync() or attach() methods.

Laravel relations doc

Nikita
  • 408
  • 3
  • 9
0

Laravel provides us with concept of pivotwhen defining N-M relationships. By default the table will have the both connected keys. But if you want to add extra fields in that bridge table.

$model->belongsToMany('Model')->withPivot('column1', 'column2');

In above case, your pivot table will have two additional columns and you can access these columns as:

$model->pivot->column1
$model->pivot->column2
Farooq Ahmed Khan
  • 3,975
  • 3
  • 27
  • 36