Fix migrations in Laravel

laravel framework csrf

Introduction

Fix migrations error in Laravel, this database migration error happens when you try to run the migration:refresh command and migration files are not written correctly.

It is important that you write well stuctured migrations as it will save you having many problems when creating a new one, or applying changes to your database scheme.

Error you may encounter can look similar to this one:

 
 
 
 
  root@machine:/# php artisan migrate:refresh
                                                                       
  [Illuminate\Database\QueryException]                                         
  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'plan'  
  ; check that column/key exists (SQL: alter table `users` drop `plan`  
  `)                                                                           

  [Doctrine\DBAL\Driver\PDOException]                                          
  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'plan'  
  ; check that column/key exists                                               
                                                                               
  [PDOException]                                                               
  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'plan'
  ; check that column/key exists                                               
                                                                               

This is caused by migrations not being symmetric:

  • function up: create, alter tables / columns
  • function down: delete tables / columns

Fix migrations in Laravel



// database/migrations/sample_migration.php
    
class CreateUsersTable extends Migration
{


    public function up()
    {
        Schema::table('users', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
        });
    }

    public function down()
    {
        Schema::drop('users');
    }
    
}