Rafa Rafael
May 10 · 2 min read

Make a Laravel Artisan Command that will Seed Data in the Database

Seeding dummy data to the database is so useful when we are still developing our app and having able to see the results when we want to manipulate the data.

We can do database seeding for this or another way and a more flexible creating your own artisan command.

On this example I will show you how easy to create it and run the command when you wanted to seed your data.

Package Used:

  1. Spatie Laravel Permission

I already created factories for Students, Teacher and Users and done setting up Spatie’s necessary configuration. To make more focus on making the command I did not included it on this story.

User’s Table

id | username | email | first_name | last_name | timestamps

Teacher’s Table

id | user_id | name | timestamps

Student’s Table

id | user_id | name | timestamps

Classroom’s Table (Pivot Table)

id | section_name | student_id | teacher_id | timestamps

To create an artisan command, run php artisan make:command SeedClassroom

The process in the handle() method in step by step:

  1. Getting the options
$isNew   = $options['new'];        
$count   = $options['students'];

2. If --new option is present it will create new users with student role.

if ($isNew) {            
  $this->info('Creating classroom with '.$count.' new students');  
  $students = $this->createStudents($count);        
}

3. else or no option is present will get existing users with a student role

$this->info('Creating classroom from existing students');            $students = $this->getExistingStudents();           

4. Validate if it has existing users with student role, if no users found then create a classroom with new students

if (! isset($students) || count($students) === 0) { 
  $this->info('No existing students found, creating classroom with 50 new students instead');                
  $students = $this->createStudents($count);            
}

5. Create a teacher for the classroom

$teacher = factory(User::class)->create();        
$teacher->assignRole('Teacher');

6. then loop through the users that created, if --new option is present assign the student role to the users otherwise save the teacher and student records to the classroom pivot table

$students->map(function ($student) use ($isNew, $teacher) { 
  $isNew ? $student->assignRole('Student')                    
         : $teacher->students()->attach($student->id);        
});

7. Showing the message that it is done

$this->info('Done creating classroom');

8. A reusable method for creating users

private function createStudents($count)    {        
  return factory(User::class, (int)$count)->create();    
}

9. A reusable method in getting existing users with a student role

private function getExistingStudents()    {        
  return User::role('Student')->get();    
}

Enjoy!

Rafa Rafael

Written by

Full Stack Developer (Laravel/Vue.js)