How to fix Laravel Migration Errors: Syntax error or access violation

Laravel migration is a way that makes you to create a table in your database. Migrations act like a version control for your database. They allow your team to change and share your application’s database schema. However, at times we may face certain migration errors. For example, any syntax error or access violation, 1071 Specified key was too long, or max key length is 767 bytes. Let’s check out some best ways we can fix Laravel Migration Errors.

The Laravel Schema façade gives unbelievable database support that helps create and manipulate tables across entire Laravel’s supported database systems.

As per the official Laravel 7.x documentation, we can easily solve migration errors.

Option 01:

You may Update your /app/Providers/AppServiceProvider.php to make it contain:

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    \Schema::defaultStringLength(191);
}

This sets a default key length using the defaultStringLength to 191. You can pass any length as per your need and to avoid the error.

Alternatively, you can enable the innodb_large_prefix option for your database. Refer to your database’s documentation for instructions to learn for how to properly enable this option.

Note: Be careful about this solution. If you index email fields for example, even the already stored emails can have a max length of only 191 chars. This is less than the official RFC states.

Option 2:

Change the charset code as follows.

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

to

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',

This should work, although you won’t be able to store extended multibyte characters like emoji.