Migration index too long? Choose the name yourself!

Migrations are a great way of building database schema, but sometimes it's harder to deal with more than just columns. One of more interesting things are indexes. In particular, I had a problem of auto-assigning a name to unique index, which appeared to be too long. What to do with it? A specific example - let's say you want to set up a unique index on four columns:
$table->unique(['product_id', 'company_id', 'price', 'delivery_hours']);
With that you can run into this error:
SQLSTATE[42000]: Syntax error or access violation:
1059 Identifier name
'prices_history_product_id_company_id_price_delivery_hours_unique'
is too long
The thing is that Laravel is trying to automatically assign a name to the index, and MySQL has a limit here: 64 characters for identifier name. Solution is to specify your own name for the structure. If you read official laravel documentation, it's not mentioned, the examples are pretty simple: 1228_laraveldaily_unique But if you dig deeper, then the exact function unique() is defined like this:
unique(string|array $columns, string $name = null)
Which means that you can specify your own name for the index.
$table->unique(['product_id', 'company_id', 'price', 'delivery_hours'],
  'prices_history_index_unique');
Notice: Just make sure it's not longer than 64 characters and is not among MySQL reserved words. Notice 2: Same rule applies to other index identifiers - functions primary() or just index() -you can specify the names as well, instead of allowing Laravel to auto-assign the names.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month

Written by