Search code examples
phplaravelfaker

Array to string conversion error when running laravel seeders


I got ErrorException Array to string conversion error when I run the seeder.

php artisan db:seed --class=StudentSeeder

It was working fine before I make changes on the StudentFactory.php, I just changed all the fakers, and I don't know which one is making this trouble.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Models\Student;

class StudentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Student::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'student_name' => $this->faker->name('male'),
            'cpr' => $this->faker->creditCardNumber,
            'email' => $this->faker->safeEmail,
            'mobile' => $this->faker->e164PhoneNumber,
            'mobile2' => $this->faker->e164PhoneNumber,
            'dob' => $this->faker->date(),
            'address' => $this->faker->address,
            'live_inـstate' => $this->faker->randomElement(["UNKNOWN", "OWN", "RENT"]),
            'relationshipـstate' => $this->faker->randomElement(["UNKNOWN", "SINGLE", "MARRIED", "DIVORCED"]),
            'family_members' => $this->faker->randomNumber(),
            'family_depends' => $this->faker->randomNumber(),
            'degree' => $this->faker->text,
            'hawzaـhistory' => $this->faker->boolean,
            'hawzaـhistory_details' => $this->faker->paragraphs,
            'healthـhistory' => $this->faker->boolean,
            'healthـhistory_details' => $this->faker->paragraphs,
            'financialـstate' => $this->faker->randomElement(["UNKNOWN", "POOR", "AVERAGE", "GOOD", "EXCELLENT"]),
            'financial_details' => $this->faker->paragraphs,
            'student_notes' => $this->faker->paragraphs,
            'registration_at' => $this->faker->date(),
        ];
    }
}

Full console error:

ErrorException 

  Array to string conversion

  at vendor/laravel/framework/src/Illuminate/Support/Str.php:494
    490▕ 
    491▕         $result = array_shift($segments);
    492▕ 
    493▕         foreach ($segments as $segment) {
  ➜ 494▕             $result .= (array_shift($replace) ?? $search).$segment;
    495▕         }
    496▕ 
    497▕         return $result;
    498▕     }

      +17 vendor frames 
  18  database/seeders/StudentSeeder.php:17
      Illuminate\Database\Eloquent\Factories\Factory::create()

      +22 vendor frames 
  41  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

Solution

  • Change all the occurrences of $this->faker->paragraphs to $this->faker->paragraphs(3, true).

    The paragraphs formatter outputs an array by default. The second parameter true indicates a string should be returned instead of an array.