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?
CodePudding user response:
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.
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',
],
)
);
CodePudding user response:
do this:
Atisan::call('db:seed', [
'--class' => (seedername)'
'--force' => true
]);
instead of:
DB::table('tag_filters')->insert(
array(
[
'tag_name' => 'javascript',
'tag_color' => 'f9bc64',
],
)
);
then you will trigger the seeder you call automatically when migrating. but you have to create the seeder class and fill it in!