Skip to content

Ability to define index key length while creating schema #9293

@eidng8

Description

@eidng8

Sorry, that I have to open the issue again. Since the issue doesn't get cleared.

Following #9256, what @GrahamCampbell said is not the case. I've quoted here for convience:

I've just tried out v5.1, and got the infamous ERR1071 while doing artisan migrate, right after laravel new. I can't find out a solution to it, yet. Because table charset is utf8mb4, and the email column is (by default) varchar(255), creating a unique on it will definitely cause error. I can't find out a way to specify the key length while calling

$table->string('email')->unique();

from the 2014_10_12_000000_create_users_table.php file.

After a little digging, it seems that we'll have to modify several index related functions in the Illuminate\Database\Schema\Blueprint class, and eventually (maybe not), the Illuminate\Support\Fluent.

Any hint?

@GrahamCampbell answered

Yeh, it's possible. Pass a second param to string with the length.

$table->string('email', 128)->unique();

Continue the talk

Passing in the length to string() changes the length of the column, but not the KEY length. The email column does need to be long enough to hold the data, truncating it to 128 may break the thing.

From what I've dug up:

\Illuminate\Database\Schema\Blueprint::string is defined as:

public function string($column, $length = 255)
{
    return $this->addColumn('string', $column, compact('length'));
}

which just wraps up a call to \Illuminate\Database\Schema\Blueprint::addColumn

protected function addColumn($type, $name, array $parameters = [])
{
    $attributes = array_merge(compact('type', 'name'), $parameters);
    $this->columns[] = $column = new Fluent($attributes);
    return $column;
}

which in turn creates a Fluent instance.

I didn't dig deeper into it, except checking the generated SQL. I can't find any key length related process in the code.

A bit more to clarify, that the key length is specifically MySQL, which makes a partial index using only the start of the column, given length in bytes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions