Reputation: 3
When I start seeding my database with db:seed
, I got this error:
Call to a member function count() on null
at P:\<folderName>\<folderName>\src\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Factories\HasFactory.php:18
14▕ {
15▕ $factory = static::newFactory() ?: Factory::factoryForModel(get_called_class());
16▕
17▕ return $factory
➜ 18▕ ->count(is_numeric($parameters[0] ?? null) ? $parameters[0] : null)
19▕ ->state(is_array($parameters[0] ?? null) ? $parameters[0] : ($parameters[1] ?? []));
20▕ }
21▕
22▕ /**
1 P:\<folderName>\<folderName>\src\database\seeders\UserSeeder.php:23
App\Models\UserPhoto::factory()
2 P:\<folderName>\<folderName>\src\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:36
Database\Seeders\UserSeeder::run()
I tried to override the default factory, following the example in the Documentation, but it did not help.
Here's my model:
class UserPhoto extends Model
{
use HasFactory;
/**
* Create a new factory instance for the model.
*/
protected static function newFactory()
{
return UserPhotoFactory::new();
}
}
If I delete ->has(UserPhoto::factory(1))
Users table seeds normally
Seeder:
class UserSeeder extends Seeder
{
public function run()
{
$city = City::first();
User::factory(15)
->for($city)
->has(UserPhoto::factory(1))
->create()
;
// UserPhoto::factory();
}
}
Factory:
class UserPhotoFactory extends Factory
{
protected $model = UserPhoto::class;
public function configure()
{
$this->afterCreating(function (UserPhoto $photo) {
$height = $this->faker->numberBetween(100, 900);
$width = $this->faker->numberBetween(100, 900);
$contents = file_get_contents('www.placecage.com/c/'.$height.'/'.$width);
$path = 'users/images/'.$photo->user_id.'/'.$photo->id.'.jpg';
Storage::disk('local')->put($path, $contents);
});
}
public function definition()
{
return [
// 'created_at' => Carbon::now()
];
}
}
User Model:
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $hidden = [
'password',
];
public function city() {
return $this->belongsTo(City::class);
}
public function photos() {
return $this->hasMany(UserPhoto::class);
}
}
Upvotes: 0
Views: 1250
Reputation: 1193
Try to check the relationship name of UserPhoto in City
Model, I assume you are using userPhoto
so I passed it as 2nd arg in has(UserPhoto::factory(), 'userPhoto')
class UserSeeder extends Seeder
{
public function run()
{
$city = City::first();
User::factory(15)
->for($city)
->has(UserPhoto::factory(1), 'userPhoto')
->create()
;
}
}
Upvotes: 0