Posts Learn Components Snippets Categories Tags Tools About
/

How to Populate Laravel Database inside the Migration File

Learn how to populate Laravel database inside the migration file to easily have a data when running the migration command

Created on Nov 16, 2021

285 views

In this short snippet, you will learn how to populate records from within the Laravel database migration file. For this scenario imagine wanting to add some records for the posts table. To do that you can write your code like below.
<?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->timestamps();
        });
        
        $posts = [
            ['title' => 'Hello John'],
            ['title' => 'Hello Jane'],
            ['title' => 'Hello Bob']
        ];
        
        foreach ($posts as $postData){
            $post = new \App\Models\Post(); /* The Post is the model for your migration */
            $post->title = $postData['title'];
            $post->save();
        }
        
        /* do note that the created_at and updated_at is automatically added */
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
It's important to have the schema definition first and then only have the data looped to insert into the database.
<?php

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->timestamps();
});
In this case, we are inserting the data by using the Eloquent model itself.
<?php

$posts = [
    ['title' => 'Hello John'],
    ['title' => 'Hello Jane'],
    ['title' => 'Hello Bob']
];

foreach ($posts as $postData){
    $post = new \App\Models\Post(); /* The Post is the model for your migration */
    $post->title = $postData['title'];
    $post->save();
}

/* do note that the created_at and updated_at is automatically added */

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)