Reputation:
I get this error when trying to run a factory in laravel 8. I've looked though several posts about this error but they all seem to come from saving/creating directly incorrectly. Not using a factory. So I am not sure why the factory isn't saving it correctly.
My migration has:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('slug');
$table->string('name');
$table->longText('desc');
$table->foreignId('user_id')->constrained();
$table->timestamps();
$table->softDeletes();
});
}
My model has:
class Post extends Model
{
use HasFactory, SoftDeletes;
public function user()
{
return $this->belongsTo(User::class);
}
public function setSlugAttribute($value)
{
$this->attributes['slug'] = Str::slug($this->name);
}
}
My factory has:
public function definition()
{
return [
'name' => $this->faker->words,
'desc' => $this->faker->sentence,
'user_id' => rand(1,10)
];
}
And my Posts seeder has:
public function run()
{
Post::factory()->times(13)->create();
}
My main DatabaseSeeder runs a user seeder that seeds 10 users. Then a post seeder to seed 13 posts.
I run php artisan migrate:fresh --seed
and it fails when it gets to the Post Seeder with this error:
TypeError
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 886
at vendor/laravel/framework/src/Illuminate/Database/Grammar.php:136 132▕ * 133▕ * @param array $values 134▕ * @return string 135▕ */ ➜ 136▕ public function parameterize(array $values) 137▕ { 138▕ return implode(', ', array_map([$this, 'parameter'], $values)); 139▕ } 140▕
+1 vendor frames 2 [internal]:0 Illuminate\Database\Query\Grammars\Grammar::Illuminate\Database\Query\Grammars\{closure}("Odio
voluptatem quis facere possimus ut.", "desc")
+13 vendor frames 16 database/seeders/PostsSeeder.php:17 Illuminate\Database\Eloquent\Factories\Factory::create()
I'm really not understanding why its expecting an array for a string column.
Upvotes: 4
Views: 6180
Reputation: 35180
'name' => $this->faker->words
will return an array of words.
You can either call the underlying method and tell it to return a string by passing true as the 2nd argument:
$this->faker->words(3, true) // 3 is the number of words which is the default
or you could use something like sentence
$this->faker->sentence
Upvotes: 9