title: Laravel - Seeding Many-to-Many Relationship
body: <p>I have a <strong><code>users</code></strong> table and a <strong><code>roles</code></strong> table that has a <strong>many-to-many</strong> relationship. These two tables are connected to a junction table called <strong><code>role_user</code></strong>.</p>
  <p><a href="https://i.stack.imgur.com/vw43I.png" rel="noreferrer">This is a model of the tables and its connections.</a></p>
  <p>Below are the Models in my Laravel project:</p>
  <p><strong>User</strong></p>
  <pre><code>namespace App;
  
  use Illuminate\Database\Eloquent\Model;
  
  class User extends Model
  {
      public function roles()
      {
          return $this-&gt;belongsToMany('App\Role');
      }
  }
  </code></pre>
  <p><strong>Role</strong></p>
  <pre><code>namespace App;
  
  use Illuminate\Database\Eloquent\Model;
  
  class Role extends Model
  {
      public function users()
      {
          return $this-&gt;belongsToMany('App\User');
      }
  }
  </code></pre>
  <p>Below is the Factory file in the Laravel project:</p>
  <pre><code>$factory-&gt;define(App\User::class, function (Faker\Generator $faker) {
      return [
          'name' =&gt; $faker-&gt;name,
          'email' =&gt; $faker-&gt;unique()-&gt;safeEmail,
          'password' =&gt; $password ?: $password = bcrypt('secret'),
      ];
  });
  
  $factory-&gt;define(App\Role::class, function (Faker\Generator $faker) {
      return [
          'role' =&gt; $faker-&gt;realText($maxNbChars = 2),
          'description' =&gt; $faker-&gt;realText($maxNbChars = 20),
      ];
  });
  </code></pre>
  <p>Below is the Seed file in the Laravel project:</p>
  <pre><code>public function run()
  {
      factory(App\User::class, 50)-&gt;create()-&gt;each(function ($u) {
          $u-&gt;roles()-&gt;save(factory(App\Role::class)-&gt;make());
      });
  
      factory(App\Role::class, 20)-&gt;create()-&gt;each(function ($u) {
          $u-&gt;users()-&gt;save(factory(App\User::class)-&gt;make());
      });
  }
  </code></pre>
  <p>This should populate the <strong><code>users</code></strong> table and the <strong><code>roles</code></strong> table but how do I go about populating the <strong><code>role_user</code></strong> table? (I don't have a Model file for the junction table.)</p>
  <p>I'm very new at this so any help would be appreciated. Thanks.</p>