fix: newsSeeder for pivot table

This commit is contained in:
K Muller 2025-12-17 10:50:12 +01:00
parent ea8db4b639
commit 541c871bcb
2 changed files with 15 additions and 21 deletions

View file

@ -28,17 +28,7 @@ class NewsFactory extends Factory
'status' => collect(NewsStatusEnum::cases())->random(),
'picture_alt' => fake()->sentence(6, true),
'picture_title' => fake()->sentence(6, true),
'picture' => 'temp.jpg',
];
}
public function configure()
{
return $this->afterCreating(function (News $news) {
$collection = NewsCategory::all();
$count = $collection->count();
$take = min($count, rand(1, 3));
$categories = $collection->random($take)->all();
$news->categories()->sync($categories);
});
}
}

View file

@ -3,6 +3,7 @@
namespace Database\Seeders;
use App\Models\News;
use App\Models\NewsCategory;
use Illuminate\Database\Seeder;
use Uwil\LaravelCommon\Helpers\FileHelper;
@ -15,15 +16,18 @@ class NewsSeeder extends Seeder
*/
public function run(): void
{
News::factory(100)->make()
->each(function ($model) {
$model->picture = FileHelper::storeFile(
$model,
new \SplFileInfo(\resource_path(
'../database/factories/assets/news/525x295.jpg'
))
);
$model->saveOrFail();
});
$categoriesIds = NewsCategory::pluck('id');
News::factory(10)->create()->each(function (News $news) use ($categoriesIds) {
$news->picture = FileHelper::storeFile(
$news,
new \SplFileInfo(
resource_path('../database/factories/assets/news/525x295.jpg')
)
);
$news->save();
$news->categories()->attach(
$categoriesIds->random(rand(1, 3))->all()
);
});
}
}