Back

Argument 1 must be of the type array when seeding random data


mark2016 posted 8 months ago

Hi I'm fairly new to Laravel and the way sync handles collections or array has me stumped when syncing a many-to-many relation. I have this code which works fine, connects a teacher to 2,3 or 4 students via a many-to-many relation:

        factory(App\Teacher::class, 5)->create()->each(function ($teacher) {
            $teacher->students()->sync(App\Student::all()->random(rand(2,4))
            );
        });

But similar code fails if there is only a single student sync'ed:

        factory(App\Teacher::class, 5)->create()->each(function ($teacher) {
            $teacher->students()->sync(App\Student::all()->random(1)
            );
        });

  [ErrorException]
  Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatSyncList() must be of the type array, object given

I assume it is due to the App\Student::all()->random(1) returning a Student while the previous App\Student::all()->random(3) returns a collection. (I checked what is returned via dd() ) I've tried wrapping things up with variations on

        factory(App\Teacher::class, 5)->create()->each(function ($teacher) {
            $teacher->students()->sync(collection([App\Student::all()->random(1)])
            );
        });

I've tried variations on the collection theme but I think I'm on the wrong track, what am I missing please.

lagbox replied 8 months ago

What version of Laravel are you using?

mark2016 replied 8 months ago

Using Laravel 5.2


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us