Support the ongoing development of Laravel.io →
Database Testing

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.

Last updated 3 years ago.
0

What version of Laravel are you using?

0

Using Laravel 5.2

0

Sign in to participate in this thread!

Eventy

Your banner here too?

mark2016 mark2016 Joined 10 Apr 2017

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.