Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
Laravel Migration Error: Syntax error or access violation: Specified key was too long; max key length is 767 bytes
š§ Oh no! You've encountered a pesky error while running Laravel migration. Don't worry, we've got you covered with this helpful guide to overcome the "Specified key was too long; max key length is 767 bytes" error. Let's dive in and fix this together!
What's the Cause of the Error?
š This error usually occurs when trying to create a unique key index on a column that has a string-based data type with a length larger than 767 bytes. The maximum key length in MySQL is limited to 767 bytes when using the InnoDB storage engine and the utf8mb4 character set.
Why Does This Error Happen with Laravel's make:auth
Command?
š When you run php artisan make:auth
command in Laravel, it generates the default User migration file which includes a unique index on the email
column. This becomes problematic when you have set the default string length to something larger than 255 characters.
How to Fix the Error?
š” Luckily, there are a couple of solutions to resolve this issue. Choose the one that suits your requirement:
Solution 1: Manually Set String Lengths
In your
AppServiceProvider
class, add the following line inside theboot
method:use Illuminate\Support\Facades\Schema; // ... public function boot() { Schema::defaultStringLength(191); // Add this line // ... }
This will set the default string length to 191 characters, allowing the unique index to be created successfully.
Solution 2: Change Database Configuration
Another approach is to change the database configuration in your
.env
file. Open the.env
file and look for theDB_DATABASE
entry. Modify or add thecharset
andcollation
values as shown below:DB_DATABASE=your_database_name DB_CHARSET=utf8 DB_COLLATION=utf8_unicode_ci
By specifying
utf8
character set andutf8_unicode_ci
collation, you'll ensure that the key length is within the permitted limit.
Try it Out!
š Implementing either of the solutions should resolve the migration error. Give it a whirl and enjoy seamless Laravel migrations!
Share Your Success Story!
š¢ If this guide has helped you overcome the "Specified key was too long" error, share your success story and help fellow developers who might be facing the same issue. We'd love to hear from you! Comment below or reach out on our social media channels.
š Stay tuned for more useful tech tips & tricks on our blog. Happy coding! š