DEV Community 👩‍💻👨‍💻

Morcos Gad
Morcos Gad

Posted on • Updated on

Make Factory More Organized - laravel

In Factory, it is possible to have in one table more than one set of fields, each sum expressing a specific category. It is better to put them in a different function for each of them :-

    public function doctor()
    {
        return $this->state(function (array $attributes) {
            $workDays = ['I, III, V', 'II, IV'];

            return [
                'role_id' => User::ROLE_DOCTOR,
                'doctor_licence_no' => $this->faker->bothify('???-######'),
                'doctor_licence_start_date' => $this->faker->dateTimeBetween('-15 years', '-3 years'),
                'doctor_licence_end_date' => $this->faker->boolean(35) ? $this->faker->dateTimeBetween('-3 years', '-10 days') : null,
                'doctor_stamp_number' => $this->faker->randomNumber(6),
                'doctor_hospital_name' => $this->faker->company(),
                'doctor_specialty' => $this->faker->jobTitle(),
                'doctor_department' => $this->faker->catchPhrase(),
                'doctor_biography' => $this->faker->text(1000),
                'doctor_work_days' => $workDays[mt_rand(0,count($workDays)-1)],
                'doctor_work_hours' => '9-5',
            ];
        });
    }

    public function patient()
    {
        return $this->state(function (array $attributes) {
            $genres = ['male', 'female'];

            return [
                'role_id' => User::ROLE_PATIENT,
                'patent_birth_date' => $this->faker->date(),
                'patient_declared_address' => $this->faker->address(),
                'patient_home_address' => $this->faker->address(),
                'patient_phone_no' => $this->faker->phoneNumber(),
                'patient_gender' => $genres[mt_rand(0,count($genres)-1)],
                'patient_personal_code' => $this->faker->randomNumber(9),
                'patient_social_number' => $this->faker->randomNumber(6).'-'.$this->faker->randomNumber(6),
                'patient_last_visit_time' => $this->faker->dateTime(),
                'patient_last_visit_reason' => $this->faker->words(rand(2,3), true),
                'patient_description' => $this->faker->text(1000),
            ];
        }); 
   }
Enter fullscreen mode Exit fullscreen mode

Then in Seeder you call what you want to do :-

User::factory(100)->doctor()->create();
User::factory(1000)->patient()->create();
Enter fullscreen mode Exit fullscreen mode

Source:-

https://github.com/LaravelDaily/Laravel-Users-Admin-Doctor-Patient/blob/main/database/factories/UserFactory.php

https://github.com/LaravelDaily/Laravel-Users-Admin-Doctor-Patient/blob/main/database/seeders/UserSeeder.php

I hope someone can benefit from it.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.