How To Insert Dummy Records Using Factory In Laravel

Sometimes we are testing your Laravel app that time we need some records in the database. So, we are added manually to fake records in the database.

The factory, faker, seeders, and tinker commands are used to generate and create the Laravel fake and dummy data in the database. Using this, we can add more than a thousand records to the database in minutes.

In this article, we are going to learn how to insert dummy records using a factory in Laravel.

Step 1: Install Laravel APP

Let’s start by creating a new project named Codhubs. To do this, run the following command:

composer create-project laravel/laravel Codehubs

Install and create a new Laravel project.

Step 2: Configure Database with Codehubs App

After installing the Codehubs Laravel application we will need to configure our database for it to work.

Go to http://localhost/phpmyadmin/

Create a new Database. For example: create a codehubs database in my localhost.

Now Configure the database in the .env file with this app:

DB_CONNECTION=mysql // add your database connection name
DB_HOST=127.0.0.1 // add your database host name
DB_PORT=3306 // add your database port
DB_DATABASE=codehubs // add your database name
DB_USERNAME=root // add your database username
DB_PASSWORD= // add your database password

With everything configured it’s time to run our app and see what it looks like.

To run the application, type the following command:

php artisan serve

For more information on how to set up laravel project go here.

Step 3: Create Model and Migration

Create one model and migration on your using the following command:

php artisan make:model Post -m

Now your Post model is created in the app\Models directory.

Creating create_posts_table.php Migration file in database\migrations directory.

Please open the create_posts_table.php file and update it with the below code:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
      $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

In this code, we have created a post table.

after that, found the Post.php modal inside the app/Models directory and update the following code into it:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'description'
    ];
}

In this, we have protected the title and description fields. $fillable attribute is an array containing all those fields of the table which can be filled using the mass assignment.

Mass assignment refers to sending an array to the model to directly create a new record in the Database.

After executing the following command on the command prompt for migrating the database.

php artisan migrate

Now your table is created in your local.

Step 4: Create Factory Class

To create a factory, execute the make:factory command:

php artisan make:factory FactoryName --model=modelName

Now go to your database/factories directory, There is a new factory class that will be created.

Open the PostFactory.php file and update it with the below code:

<?php

namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;


class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->title,
            'description' => $this->faker->text,
        ];
    }
}

Step 5: Run tinker and Factory Command

What’s Tinker?

The tinker commands that you can run with php artisan tinker. The command allows you to interact with a database without creating the routes and you can use it to run code within the context of your application.

This is a command tool that works with a PHP artisan and creates objects or modifies the data. A tinker works with a database means it allows you to create the objects, insert the data, etc.

Now it’s time to execute the following command on the command prompt to generate or create dummy data using the tinker and factory command:

php artisan tinker
Post::factory()->count(20)->create()

Output:

Now go to http://localhost/phpmyadmin/ and check the database posts table.

Thank you, I hope you find something helpful. 😉

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories