Posts Learn Components Snippets Categories Tags Tools About
/

How to Prevent Key Is Too Long Error in Laravel

Learn how to fix and prevent key is too long error in Laravel project the easy way

Created on Oct 28, 2021

117 views

Sometimes you might come across an error saying 'specified key is too long" when defining a migration in Laravel and there are several ways to fix this issue.
[Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
The cause of the error above is because of a number that's higher than 255 characters so by specifying the code below you will get the error message as mentioned above.
<?php $table->string('email', 300);

Method 1: Specify Smaller Value


The easiest fix for this issue is to just update the columns and specify the value of the particular field to 255 characters.
<?php $table->string('email', 255);

Method 2: Update config/database.php Configuration


The next fix is to update the "configuration database" which is located in the "config" folder.
config/database.php 
The value of the charset and collation should be updated to below.
<?php

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

Method 3: Update defaultStringLength value


The 3rd method is to update the defaultStringLength to have a value of 191 and this should fix the error.
<?php

Schema::defaultStringLength(191);

Schema::create('users', function (Blueprint $table) {
    // your columns definition
});

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)