Home > Database > Mysql Tutorial > Laravel Migration Error: How to Fix 'Unique Key Length Exceeds Limit'?

Laravel Migration Error: How to Fix 'Unique Key Length Exceeds Limit'?

Susan Sarandon
Release: 2024-12-05 17:52:11
Original
894 people have browsed it

Laravel Migration Error: How to Fix

Laravel Migration Error: Unique Key Length Exceeds Limit

When attempting to migrate a users table in Laravel using a migration, developers may encounter the error: "[SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes." This error typically arises when the specified unique key is longer than the maximum allowable length.

Problem Statement

The provided migration attempts to create a users table with a unique key on the email column. However, the email column is specified to have a length of 320 characters, exceeding the maximum length limit.

Solution

1. Reduce Email Column Length

Reduce the length of the email column to a smaller value, such as 250 or the default of 191 characters. Adjust the migration as follows:

Schema::create('users', function(Blueprint $table)
{
    // ...

    $table->string('email', 250); // Update the email column length

    // ...
});
Copy after login

2. Set Default String Length (Laravel 5.4 )

If you're using Laravel 5.4 or higher, you can set a default string length in the boot method of the AppServiceProvider.php file:

public function boot()
{
    Builder::defaultStringLength(191);
}
Copy after login

This will set a default length of 191 characters for all string columns created in migrations, ensuring that unique keys do not exceed the allowable length.

The above is the detailed content of Laravel Migration Error: How to Fix 'Unique Key Length Exceeds Limit'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template