Home / Snippets / How to Populate Laravel Database inside the Migration File
How to Populate Laravel Database inside the Migration File cover

How to Populate Laravel Database inside the Migration File

295

2 years ago

0 comments

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 */
notion avatar

Ahabz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this