Search code examples
phplaravellaravel-seedinglaravel-factory

Laravel seeding - Array to string conversion


I am having this 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, // <-- line 17 where is failing on stacktrace
            ]);
        }
    }
}

This is the code of my 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,
            ];
        });
    }
}

However when I try to run this seeder I get the following error


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"])

I am getting very confused because if I dd($foo) inside the foreach loop the value I get is a string type. Any ideas what I am doing wrong?


Solution

  • That is because range() returns an array containing a sequence of the given numbers (in your case from 0 to 4 inclusive).

    If you want each parent_id to have any value somewhere between 0 and 4 (inclusive), then you should use something like rand(0, 4) instead.