Ash
Ash

Reputation: 3429

array_merge error during seeder whilst loading eloquent data

Synopsis

I have ran into a very confusing problem with . Essentially what I have are a number of seeders which loads data from a JSON document and inserts into the database using - this works fine.

I have a final seeder which loops through some data, during this loop I load a record using but the moment I try to access the data I receive the following error:

  [ErrorException]                            
    array_merge(): Argument #1 is not an array

Seeder Snippet

foreach ($data as $country => $states) {
    $countryId = Country::where('iso2_code', $country)->first()->pluck('id');

    dd($countryId); // ErrorException

    array_walk($states, function (&$value) use ($countryId) {
        $value = ['country_id' => $countryId, 'name' => $value];
    });

    State::insert($states);
}

The confusing part about this error is if I do not use Eloquent my problem is solved, as per:

foreach ($data as $country => $states) {
    $countryId = DB::table((new Country)->getTable())
        ->select('id')
        ->where('iso2_code', $country)
        ->first();

    dd($countryId->id); // Works.

    array_walk($states, function (&$value) use ($countryId) {
        $value = ['country_id' => $countryId, 'name' => $value];
    });

    State::insert($states);
}

Why is it then that DB works as expected but Eloquent triggers some array_merge error?

Upvotes: 1

Views: 241

Answers (1)

Ash
Ash

Reputation: 3429

The Solution

In my situation I was setting protected $dates = false on my model. Where typically as per the documentation I should be using public $timestamps = false or protected $dates = array();.

Upvotes: 1

Related Questions