Firstly i was getting an error in
php artisan migrate
as
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
and Then i found a post on laracasts
to fix this as
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
After adding this, when i run
php artisan optimize
then i am presented with new error as below
Call to undefined method Illuminate\Database\Schema\MySqlBuilder::defaultStringLength()
Please assist in getting rid of all these errors.
defaultStringLength
is introduced in Laravel v5.4. Reference.
You can update the Laravel version
OR
You specify the length as $table->string('coumname', 255);
You cannot specify more than 255
. If you leave the length parameter it will assign 255
by default
This is because Laravel 5.4 uses the utf8mb4 character set by default, which includes support for storing “emojis” in the database. You can choose any one from these 2 solutions:
1) Change
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
to
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
2) Edit AppServiceProvider located at App\Providers\AppServiceProvider.php and add the following line to the boot() method and load the Schema facade:
use Illuminate\Support\Facades\Schema;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
What that will do is actually change the default maximum field length in the database and actually shorten your maximum string length from 255 to maximum of 191 characters (utf8 uses 3 bytes per character while utf8mb4 uses 4 bytes per character your field can now hold 25% less characters 255 * 75% = 191.25). So if you don’t set the string field by hand in the migration the new default will be 191.
Find AppServiceProvider in Laravel Project
1.First Add Facade
use Illuminate\Support\Facades\Schema;
2.Add Below lines in boot function
function boot() {
Schema::defaultStringLength(191);
}
If Laravel < 5.4
1. Find AppServiceProvider in Laravel Project
2. Comment line or remove Schema::defaultStringLength(191) in boot method