2
votes

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()
1

1 Answers

4
votes

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.