Call to undefined method Illuminate\Database\Schema\MySqlBuilder::defaultStringLength()

17,126

Solution 1

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

Solution 2

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.

Share:
17,126
Gags
Author by

Gags

I am a Web Designer and Developer with still a lot more to learn and skills as PHP Laravel Angular React jQuery HTML 5 Bootstrap MySQL Database

Updated on June 04, 2022

Comments

  • Gags
    Gags almost 2 years

    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.

    • Saumini Navaratnam
      Saumini Navaratnam about 7 years
      What is your laravel version?