phplaravelmigrationmysql-error-1146

Populating a database in a Laravel migration file


I'm just learning Laravel, and have a working migration file creating a users table. I am trying to populate a user record as part of the migration:

public function up()
{
    Schema::create('users', function($table){

        $table->increments('id');
        $table->string('email', 255);
        $table->string('password', 64);
        $table->boolean('verified');
        $table->string('token', 255);
        $table->timestamps();

        DB::table('users')->insert(
            array(
                'email' => `name@domain.example`,
                'verified' => true
            )
        );

    });
}

But I'm getting the following error when running php artisan migrate:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vantage.users' doesn't exist

This is obviously because Artisan hasn't yet created the table, but all the documentation seems to say that there is a way of using Fluent Query to populate data as part of a migration.

Anyone know how?


Solution

  • Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:

    public function up()
    {
        // Create the table
        Schema::create('users', function($table){
            $table->increments('id');
            $table->string('email', 255);
            $table->string('password', 64);
            $table->boolean('verified');
            $table->string('token', 255);
            $table->timestamps();
        });
    
        // Insert some stuff
        DB::table('users')->insert(
            array(
                'email' => 'name@domain.example',
                'verified' => true
            )
        );
    }