Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the MySQL datatype SET equivalent in Laravel Schema?

Laravel Schema has a command for ENUM equivalent to the table. What is the SET equivalent to the table?

like image 892
Debiprasad Avatar asked Jun 18 '14 14:06

Debiprasad


People also ask

Does Laravel work with MySQL?

Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server.

What is database schema in Laravel?

The Laravel Schema class provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems.

Which DB to use with Laravel?

Currently, Laravel provides first-party support for five databases: MariaDB 10.3+ (Version Policy) MySQL 5.7+ (Version Policy) PostgreSQL 10.0+ (Version Policy)

How do I change the datatype of a column in Laravel migration?

How to change data type of column in laravel 9 migration ? Step 1 : Install doctrine/dbal package. Step 2 : Generate migration file. Step 3 : Open generated migration file and update.


1 Answers

Step 1. Extend default classes(add this code to your migration file after use sections):

class ExtendedBlueprint extends Blueprint {

    /**
     * Create a new set column on the table.
     *
     * @param  string  $column
     * @param  array   $allowed
     * @return \Illuminate\Support\Fluent
     */
    public function set($column, array $allowed)
    {
        return $this->addColumn('set', $column, compact('allowed'));
    }

}


class ExtendedMySqlGrammar extends Illuminate\Database\Schema\Grammars\MySqlGrammar {

    /**
     * Create the column definition for an set type.
     *
     * @param  \Illuminate\Support\Fluent  $column
     * @return string
     */
    protected function typeSet(\Illuminate\Support\Fluent $column)
    {
        return "set('".implode("', '", $column->allowed)."')";
    }

}

Step 2. Then, we need to change default grammar and blueprint classes to our custom:

// set new grammar class
DB::connection()->setSchemaGrammar(new ExtendedMySqlGrammar());

// get custom schema object
$schema = DB::connection()->getSchemaBuilder();

// bind new blueprint class
$schema->blueprintResolver(function($table, $callback) {
    return new ExtendedBlueprint($table, $callback);
});

// then create tables 
$schema->create('table name', function(ExtendedBlueprint $table)
{
    $table->increments('id');
    $table->text('sentence');
    $table->string('author')->nullable();
    $table->string('source')->nullable();
    $table->set('difficulty', range(1, 10)); // use our new mysql type 
    $table->boolean('enabled')->default(true);
});

This method will also work after composer update, because we did not edited any framework code.

like image 136
Roman Nazarkin Avatar answered Oct 16 '22 18:10

Roman Nazarkin