title: Laravel 8: How to seed a pivot table in many to many relationship
body: <p>I want to seed my tables via seeder/factory.
  I want to seed a Pivot table, which connects the tables <code>atg</code> and <code>debtor</code> and is called <code>atg_debtor</code>, which hast an <code>id</code>, <code>created_at</code>, <code>updated_at</code>, <code>atg_id</code>, <code>debtor_id</code>.</p>
  <p>When inserting data via Eloquent everything works fine. When I try to seed my db with Seeders/Factory it always tries to insert data to my <code>atg</code> table, which I don´t want. I want to seed the <code>debtor</code> table (that works fine) and the pivot table with a given <code>atg_id</code> and the dynamic <code>debtor_id</code>, which is created whilst seeding the debtor.</p>
  <p>My Debtor Model:</p>
  <pre><code>&lt;?php
  
  namespace App\Models;
  
  use App\Models\Atg;
  use Illuminate\Database\Eloquent\Model;
  use Illuminate\Database\Eloquent\Factories\HasFactory;
  
  class Debtor extends Model
  {
      use HasFactory;
  
      public function atg()
      {
          return $this-&gt;belongsToMany(Atg::class)-&gt;withTimestamps();
      }
  }
  </code></pre>
  <p>The DebtorSeeder:</p>
  <pre><code>&lt;?php
  
  namespace Database\Seeders;
  
  use App\Models\Atg;
  use App\Models\Debtor;
  use Illuminate\Database\Seeder;
  
  class DebtorSeeder extends Seeder
  {
      /**
       * Run the database seeds.
       *
       * @return void
       */
      public function run()
      {
          $debitor = Debtor::factory()
                  -&gt;count(1)
                  -&gt;hasAtg(1)
                  -&gt;create();
      }
  }
  </code></pre>
  <p>The DebtorFactory:</p>
  <pre><code>&lt;?php
  
  namespace Database\Factories;
  
  use App\Models\Debtor;
  use Illuminate\Database\Eloquent\Factories\Factory;
  
  class DebtorFactory extends Factory
  {
      /**
       * The name of the factory's corresponding model.
       *
       * @var string
       */
      protected $model = Debtor::class;
  
      /**
       * Define the model's default state.
       *
       * @return array
       */
      public function definition()
      {
          return [
              'created_at' =&gt; now(),
              'created_by_id' =&gt; '3',
              'rechtsform' =&gt; 'Unternehmen',
              'name' =&gt; $this-&gt;faker-&gt;company    
          ];
      }
  }
  </code></pre>
  <p>Thank you!</p>