Laravel 8: Generating Dummy Database Data using Model Factories

Kenpachi Zaraki
3 min readMar 28, 2021

Usually, the way to fill a database table is to setup a form or some other mechanism. If you happen to need to generate dummy data to test your Laravel interface, Laravel Model Factories can be useful.

Assumptions:

This tutorial assumes that you have PHP and Composer installed on your computer. It also uses XAMPP’s Apache and MySQL installations. It is therefore assumed that the reader is familiar with XAMPP. Visit the Composer and XAMPP websites to download them.

Case Scenario:

We have a “students” table in a MySQL database called “dummy-data”. We wish to interact with this table using a “Students” model from our Laravel application. Each student has an id, name, age, email and address.

Here’s how you populate a MySQL database with dummy data:

  1. Create a new Laravel project with composer
composer create-project laravel/laravel dummy-data

2. Create corresponding database in phpMyAdmin

3. Add the new database name to your .env file

4. Create a Model, Controller, and Factory for students

Use the following line in your console

php artisan make:model Student -cfm

You should get output that looks something like this:

5. Edit the ‘create_students_table’ migration file

Add student data attributes to the migration file. Here is a snapshot of the contents of the file after the edits.

6. Edit the “StudentFactory.php” file

Add “use Illuminate\Support\Str;” to the StudentFactory.php file; then add student attributes to the definition() method thus:

7. Edit the “DatabaseSeeder.php” file

Add the following to the “DatabaseSeeder.php” file and replace the number “15” with the the number of rows you wish to generate in your “students” table

\App\Models\Student::factory(15)->create();

This is what your “DatabaseSeeder.php” file would look like after the edit.

8. Run the following on your command line

php artisan migrate --seed

Your output should look something like this:

9. Voila!! Your “students” table is populated.

--

--