Chris G
Chris G

Reputation: 7050

Laravel 5.1 testing with model relationships and factories

Currently I have 2 models (and test factories) for:

I've looked at the docs about test factories with relationships, but nothing is specifically shown for a single instance. What I have now is:

$user = factory(App\User::class)->create(); $post = factory(App\Post::class)->create(); $post->user()->save($user);

I'm currently getting the following PHPUnit error: BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::save()

I'm probably missing something small here. How can I get this to work?

Upvotes: 1

Views: 1468

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

$post->user() returns relation definition, not the related object. If you need to associate user with the post and save it, you need to do the following:

$user = factory(App\User::class)->create();
$post = factory(App\Post::class)->create();
$post->user()->associate($user);
$post->save();

Upvotes: 1

Related Questions