I have a Laravel 9 project and in the migration of one of the tables, I would like to insert some data as well when creating the table:
public function up()
{
Schema::create('tag_filters', function (Blueprint $table) {
$table->id();
$table->string('tag_name');
$table->string('tag_uri')->nullable();
$table->string('tag_color');
$table->unsignedBigInteger('tag_parent')->nullable();
$table->timestamps();
$table->foreign('tag_parent')->references('id')->on('tag_filters')->onDelete('cascade');
DB::table('tag_filters')->insert(
array(
[
'tag_name' => 'javascript',
'tag_color' => 'f9bc64',
],
)
);
});
}
But now when I run the migrations by saying php artisan migrate
, I get this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘forum.tag_filters’ doesn’t exist (SQL: insert into tag_filters
…
So what’s going wrong here?
How can I properly insert some data when creating a new table via the Migrations in Laravel?
3
Answers
Laravel creates the
tag_filters
table after the closure has been executed. So right now you’re trying to insert a record in the table that does not exists yet.Executing the insert statement after the closure will work.
do this:
instead of:
then you will trigger the seeder you call automatically when migrating.
but you have to create the seeder class and fill it in!
always always use seeders to insert data into tables and migrations to create or alter them