Laravel Seeder执行报错:Array to string conversion问题求助
问题
我编写了如下FooSeeder和FooFactory代码,运行Laravel数据填充时出现Array to string conversion错误,错误栈指向Seeder的第17行(设置parent_id的位置)。但我在foreach循环中用dd($foo)查看,$foo是字符串类型,请问问题出在哪里?
Seeder代码
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use App\Models\Foo; use Illuminate\Support\Str; class FooSeeder extends Seeder { public function run() { foreach (['Value 1', 'Value 2', 'Value 3', 'Value 4'] as $foo) { Foo::factory()->create([ 'fooName' => $foo, 'fooUsername' => Str::slug($foo), 'parent_id' => 1, // <-- 错误栈指向的第17行 ]); } } }
Factory代码
<?php namespace Database\Factories; use Illuminate\Support\Str; use Illuminate\Database\Eloquent\Factories\Factory; class FooFactory extends Factory { public function definition() { $foo = $this->faker->word(); return [ 'fooName' => $foo, 'fooUsername' => Str::slug($foo), 'parent_id' => rand(1, 5), ]; } public function noParent() { return $this->state(function (array $attributes) { return [ 'parent_id' => null, ]; }); } }
错误信息
ErrorException Array to string conversion at vendor/laravel/framework/src/Illuminate/Support/Str.php:835 831▕ 832▕ $result = array_shift($segments); 833▕ 834▕ foreach ($segments as $segment) { ➜ 835▕ $result .= (array_shift($replace) ?? $search).$segment; 836▕ } 837▕ 838▕ return $result; 839▕ } +18 vendor frames 19 database/seeders/FooSeeder.php:17 Illuminate\Database\Eloquent\Factories\Factory::create(["Value 1", "value-1"])
问题分析与解决
从错误栈最后一行可以看到,create方法接收的参数被解析成了["Value 1", "value-1"],说明传递给create的数组存在键丢失问题——parent_id键名大概率带有不可见特殊字符(比如全角空格、Tab或其他非打印字符),导致PHP无法识别该键,最终把数组当作索引数组传递,Laravel Factory处理时触发字符串转换错误。
解决步骤:
- 直接删除Seeder第17行的
parent_id => 1,,重新手动输入该代码,确保键名是纯英文半角字符,无任何隐藏符号。 - 检查
Foo模型对应的数据表,确认parent_id字段类型为整数(int或bigint),这是外键字段的常规设计。 - 重新运行数据填充命令:
php artisan db:seed --class=FooSeeder
也可以尝试通过模型赋值的方式设置parent_id,规避数组键名问题:
$fooModel = Foo::factory()->create([ 'fooName' => $foo, 'fooUsername' => Str::slug($foo), ]); $fooModel->parent_id = 1; $fooModel->save();
内容的提问来源于stack exchange,提问作者ltdev
相关产品推荐
相关产品推荐

