Ad
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.
Ad
Answer
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 insidefactory(App\Category::class)
$factory->afterCreating(Category::class, function (Category $category, $faker) {
$category->news()->save(factory(News::class)->make());
});
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad