Questionnaires
Questionnaire model factory
Why we sometimes didn't use the Questionnaire model factory. We chose not to use the Questionnaire model factory for seeding the questionnaires due to the following reasons:
- Seeded Questionnaires: We have already seeded the necessary questionnaires to the database using migration files. These seeders ensure that the required questionnaires are available in the database for use.
- Fixed Known Slugs: The Questionnaire model factory generates slugs for questionnaires using a fixed set of known slugs from the
modules/MyClic/src/Enums/QuestionnaireSlugs.php
enum file. This is done to ensure that the generated slugs correspond to the predefined values in the enum. However, since we have already seeded the questionnaires for thoseQuestionnaireSlugs
file slugs using migrations, using the Questionnaire model factory would result in duplicated questionnaires with the same slugs as we are generating the slugs inside QuestionnaireFactory to be only from QuestionnaireSlugs enum file:'slug' => Arr::random(QuestionnaireSlugs::values())
.
So, to avoid the slug duplication issue that will happen if we used Questionnaire model factory, we perform a query to the database using the Questionnaire model to retrieve random records from the already seeded questionnaires and associates them with the store.
Take a look at the following example from database/factories/StoreFactory.php
to see how we get random records from the already seeded questionnaires to add them to the store enabled questionnaires instead of using Questionnaire model factory:
php
public function configure(): static
{
return $this->afterCreating(function (Store $store): void {
$store->enabled_questionnaires()->sync(array_unique([
$store->main_questionnaire_id,
...Questionnaire::inRandomOrder()->take(3)->pluck('id'),
]));
});
}