Search code examples
phplaravellaravel-6

Factory & Seeder for Pivot Table


I am trying to create a factory and seeder for a pivot table. I am trying to do so without creating a model just for the pivot table. However, in doing so, I am getting an error. Before I show the error, here are my files:

// CategoryNewsFactory.php
use App\Model;
use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    DB::table('category_news')->insert(
      [
          'category_id' => factory(App\Category::class)->create()->id,
          'news_id' => factory(App\News::class)->create()->id,
      ]
  );
});
// CategoriesNewsSeeder.php

    public function run()
    {
        factory(App\Model::class, 35)->create();
    }

And here is my error message:

   Error

  Class 'App\Model' not found

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:232
    228|         if ($this->amount < 1) {
    229|             return (new $this->class)->newCollection();
    230|         }
    231|
  > 232|         $instances = (new $this->class)->newCollection(array_map(function () use ($attributes) {
    233|             return $this->makeInstance($attributes);
    234|         }, range(1, $this->amount)));
    235|
    236|         $this->callAfterMaking($instances);

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:169
      Illuminate\Database\Eloquent\FactoryBuilder::make([])

  2   C:\laragon\www\startup-reporter\database\seeds\CategoriesNewsTableSeeder.php:14
      Illuminate\Database\Eloquent\FactoryBuilder::create()

So I am wondering, what am I doing wrong and how can I fix it?

Thanks.


Solution

  • Firstly, you can create the model for your pivot table as far as Model class (in your case) doesn't exist at all. Secondly, you can attach/sync one model to another instead of creating a pivot record manually. Finally, you can use the following code inside factory(App\Category::class)

    $factory->afterCreating(Category::class, function (Category $category, $faker) {
        $category->news()->save(factory(News::class)->make());
    });