Forum

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

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.

mark2016
mark2016
  • 2 weeks ago

What version of Laravel are you using?

Using Laravel 5.2