2

How do I create a new instance of an eloquent model with relationships.

This is what I am trying:

$user = new User();
$user->name = 'Test Name';
$user->friends()->attach(1);
$user->save();

But I get

Call to undefined method Illuminate\Database\Query\Builder::attach()
Petah
  • 45,477
  • 28
  • 157
  • 213

1 Answers1

4

Try to attach friend after save since the attach() method needs an ID to exist on the parent model. ID's aren't (usually) generated until model is saved (when a primary key or other identifier for that model is created in the database) :

$user = new User();
$user->name = 'Test Name';
$user->save();

$user->friends()->attach(1);

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • 1
    Yep, the attach method needs an ID to exist on the parent model. ID's aren't (usually) generated until model is saved (when a primary key or other identifier for that model is created in the database) – fideloper Dec 21 '15 at 21:41
  • 1
    Thanks @fideloper for your intervention/explication, can i improve my answer with your comment? – Zakaria Acharki Dec 21 '15 at 21:43