Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migrations insert into table

In Laravel 5.3 within my up() function how can I insert data into another table?

I can only see things in the guide for updating columns etc

like image 453
Jess McKenzie Avatar asked Dec 24 '22 01:12

Jess McKenzie


1 Answers

You can do it as what you do in normal Laravel code as long as that table has been created already. For example:

public function up()
{
    Schema::create('this_table', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    });

    \DB::table('that_table')->insert([]);
}

As others suggest, you should consider if it's better to move such logic into database seeders. However, I find sometimes it's better to have such logic just live inside migration files when your table have constant initial data.

FYI, Here is an open source Laravel project does this.

===========Edit 5 years later=============

I suggest anyone want to do this consider database seeders as the original answer suggested. Now Laravel have a schema:dump command that can be used for squashing your migrations. This might be useful if you have a project with many migrations. For me, I have a project with 408 migrations and it's not easy to use the schema:dump now as data filling methods in migrations will be lost.

like image 187
yixiang Avatar answered Dec 26 '22 15:12

yixiang