Search code examples
phplaravellaravel-factory

I got error array_merge Expected parameter 2 to be in laravel 8 factory?


In Laravel 8.12 running factory from controller I got error :

[2021-01-12 16:42:10] local.ERROR: array_merge(): Expected parameter 2 to be an array, int given {"exception":"[object] (ErrorException(code: 0): array_merge(): Expected parameter 2 to be an array, int given at /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:381)
[stacktrace]
#0 [internal function]: Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError()
#1 /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php(381): array_merge()
#2 [internal function]: Illuminate\\Database\\Eloquent\\Factories\\Factory->Illuminate\\Database\\Eloquent\\Factories\\{closure}()
#3 /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/vendor/laravel/framework/src/Illuminate/Collections/Collection.php(884): array_reduce()

... In the controller I run :

Ad::addDummyData();

In app/Models/Ad.php:

public static function addDummyData() {

$ads = Ad::factory()->create(10); // POINTS TO THIS LINE
\Log::info(  varDump($ads, ' -1 addDummyData() $ads::') );

}

in database/factories/AdFactory.php :

<?php

namespace Database\Factories;

use Config;
use App\Models\Ad;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use \Cviebrock\EloquentSluggable\Services\SlugService;

class AdFactory extends Factory
{
    protected $model = Ad::class;

    public function definition()
    {
        $text= $this->faker->text;
        $slugValue = SlugService::createSlug(Ad::class, 'slug', $text);

        \Log::info(  varDump($slugValue, ' -1 $slugValue::') );
        return [
            'title' => $text,
            'ad_token' => $text,
            'slug' => $slugValue,
            'phone_display' => (rand(1, 3) == 1),
            'has_locations' => (rand(1, 4) == 1),
            'status' => 'A', // password
            'price' => mt_rand(10, 500),
            'ad_type' => (rand(1, 2) == 1 ? 'B' : 'S'),
            'expire_date' => $this->faker->dateTimeThisMonth('now', Config::get('app.timezone'))->format('Y-m-d H:i:s'),
            'description' => $this->faker->paragraphs(rand(1, 4), true),
            'creator_id' => rand(1, 5),
        ];
    }
}

In error description I did not any reference to database/factories/AdFactory.php.

Why error and how it can fixed ?

Thanks!


Solution

  • You must pass an array of attributes when using the create method. The argument is to override the factory's default model attributes.

    Here's an example from the documentation:

    $user = User::factory()->create([
        'name' => 'Abigail',
    ]);
    

    If you want to create a model 10 times, you need to use the count method:

    Ad::factory()->count(10)->create();