Summer Sale! All accounts are 50% off this week.

nategg's avatar

Pass variable to factory, Laravel 8, not working

Trying to pass a variable from DatabaseSeeder to factory in Laravel 8; is there new syntax?

I need to loop thru my users with foreach. I see a bunch of examples of passing variable to a factory as an array like this

// DatabaseSeeder.php
foreach ($users as $user) {
$round = Round::factory()->create(['user' => $user,]);
}

and I've also seen this:

$round = Round::factory()->create($user);

Most of those examples are several years old, but one is Sep'19. But neither way is working for me. I get:

// Terminal: php artisan db:seed
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined variable: user", …

My foreach loop is definitely producing valid $user (confirmed via dd($user)). My factory def looks like this:

// RoundFactory.php
return [
    'user_id' => $user,
    'other_field' => $this->faker-> …something,
    other fields …
]

So is there some other way to achieve this? Thanks.

0 likes
6 replies
bugsysha's avatar

Replace this

$round = Round::factory()->create(['user' => $user,]);

with this

$round = Round::factory()->create(['user_id' => $user->id]);
nategg's avatar

Thanks for replying. Your suggestion in the seeder is correct, but it seems my problem was in the factory definition array. My mistake was repeating the variable $user in the factory definition array,

'user_id' => $user->id. So I've changed my factory def to say

'user_id' => 'overridden' to remind me that the $user variable doesn't work.

bugsysha's avatar

Hard to figure that from what you've shown.

nategg's avatar

Not sure what you mean. I kept my reply short for time. I used your code in the DatabaseSeeder, but I had to change the RoundFactory definition as below to fix the error.

My RoundFactory definition now reads:

return [
	'user_id' => 'overridden'  // overridden is placeholder replaced by 'user_id' value from seeder
//	'user_id' => $user   // This $user variable was my original code, was causing the error
	(other fields)

The new code has worked so far, but I would appreciate any comment you have on it. Thanks much.

1 like
bugsysha's avatar

Yap, truncating your posts made impossible to give you better answer.

DerekCaswell's avatar

I know this post is 1 year old but for the benefit of others that may come across this thread, there is a built-in way to accomplish what the OP is wanting with the relationship. Assuming that the Round model has a user relationship on it, you can do this:

$round = Round::factory()->for($user)->create();

Then in the factory, you can can have this:

return [
	'user_id' => User::factory() // This will still get overwritten but it will allow for a user to be created if it is not overwritten
	(other fields)

Please or to participate in this conversation.