title: Seeding Relationship one to many in Laravel
body: <p>I need to seed a relationship in Laravel, where each user has many devices</p>
  
  <p>The User model</p>
  
  <pre><code>public function devices()
  {
      return $this-&gt;hasMany(Device::class);
  }
  </code></pre>
  
  <p>The Device model</p>
  
  <pre><code>public function users()
  {
      return $this-&gt;belongsTo(User::class);
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The device_user table</p>
  
  <pre><code>    Schema::create('device_user', function (Blueprint $table) {
          $table-&gt;increments('id');
          $table-&gt;integer('device_id')-&gt;unsigned()-&gt;index();
          $table-&gt;foreign('device_id')-&gt;references('id')-&gt;on('devices')-&gt;onDelete('cascade');
          $table-&gt;integer('user_id')-&gt;unsigned()-&gt;index();
          $table-&gt;foreign('user_id')-&gt;references('id')-&gt;on('users')-&gt;onDelete('cascade');
          $table-&gt;timestamps();
      });
  </code></pre>
  
  <p>The seeder</p>
  
  <pre><code>    factory(App\Device::class, 20)-&gt;create()-&gt;each(function(App\Device $device) {
          $device-&gt;users()-&gt;attach([
              rand(1,5), 
              rand(6,15), 
              rand(16,20), 
          ]);
      });
  </code></pre>
  
  <p>But, when I run the migration with seeder, I get this message</p>
  
  <pre><code>    Call to undefined method Illuminate\Database\Query\Builder::attach()
  </code></pre>
  
  <p>Please, help</p>