Search code examples
phpsqllaraveldatabase-migrationlumen

Laravel/Lumen migrations: How to create a permanent uppercase column?


My Laravel migration looks like this:

class CreateTableLanguage extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('language', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->char('iso639_1',2)->unique()->comment('http://www.loc.gov/standards/iso639-2/php/code_list.php');
            $table->char('locale',2)->uppercase();  // DUMMY uppercase(), does not work
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('language');
    }
}

In SQL I could force a columns' contents to be uppercase with this statement:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

How can I apply uppercase to my Laravel migrations class?


Solution

  • In Laravel you can force the content to be uppercase too with a Mutator

    public function setLocaleAttribute($value)
    {
        $this->attributes['locale'] = strtoupper($value);
    }
    

    this way, when you try to modify that field with Laravel, you will store the value in uppercase

    $language->locale = 'es'; // this will be 'ES'
    $language->save();
    

    To complement that behaviour, if you want to ensure to get the value always in uppercase in case someone else added the record manually or with a custom code, you can create an accessor

    public function getLocaleAttribute($value)
    {
        return strtoupper($value);
    }