How do you create a User instance in another factory in Laravel?

1.7k views Asked by At

I am trying to create some test data using factories in Laravel 5.5. I am running this

factory('App\Thread', 3)->create();

I get the error message Column 'user_id' cannot be null

Column 'user_id' cannot be null (SQL: insert into thread
s` (user_id, title, body, updated_at, created_at) values (, Quia modi
aperiam eos aut., Sed voluptate ut quia ut. Et accusamus eaque est amet. Veniam
consectetur exercitationem id facere., 2017-09-04 04:38:11, 2017-09-04 04:38:11)
)'

My Thread factory creates a new instance user, but it doesn't seem to return a value.

use Faker\Generator as Faker;

$factory->define(App\Thread::class, function (Faker $faker) {

return [
    'user_id' => function () {
                return factory('App\User')->make()->id;
    },
    'title' => $faker->sentence,
    'body' => $faker->paragraph,
];
});

I haven't modified the user factory at all. I have copied and pasted from the documentation and cannot get it. Any help would be appreciated I'm new to this and I'm sure it's something simple.

1

There are 1 answers

0
NinjaCoder On

I was typing

factory(App\Thread::class, 3)->create();

instead of

factory('App\Thread', 3)->create();

I did not know they were different.