9

Using Laravel 5.5 and Mysql (10.1.19-MariaDB)

For a md5 hash I want a binary(16) column. Let's call the colum url_hash

When using :

$table->binary('url_hash');

it will give me a BLOB column.

source : https://laravel.com/docs/5.5/migrations#creating-columns

I have seen all kind of hacks or plugins around the web for this , but what is the most simple one without any external plugins that could break on the next update?

Cheers

5
  • Are you using MySQL? Commented Mar 20, 2018 at 16:38
  • yes, will update .. thanks for noticing. Commented Mar 20, 2018 at 16:45
  • you could do it with DB::statement('CREATE TABLE t (url_hash BINARY(16))'); Commented Mar 20, 2018 at 17:08
  • @SariYono : Will that not create a double table? aka an error? But thanks , I think it is getting me on the right track. Commented Mar 20, 2018 at 17:34
  • you can use alter table if you prefer in a separate call ;) Commented Mar 20, 2018 at 17:35

3 Answers 3

17

You can just set the character set to binary.

$table->char('url_hash', 16)->charset('binary');

This is actually shown as a real binary column type with a length of 16 in MySQL Workbench.

There shouldn't be any difference: https://stackoverflow.com/a/15335682/5412658

Sign up to request clarification or add additional context in comments.

1 Comment

Whoever lands here, I can confirm, it really creates correct binary column in MySQL. $table->char('url_hash', 16)->charset('binary'); Results: CREATE TABLE test (url_hash binary(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
10

Extend the MySqlGrammar class, e.g. in app/MySqlGrammar.php:

namespace App;

use Illuminate\Support\Fluent;

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

    protected function typeRealBinary(Fluent $column) {
        return "binary({$column->length})";
    }

}

Then use a macro to add your own column type:

DB::connection()->setSchemaGrammar(new \App\MySqlGrammar());

Blueprint::macro('realBinary', function($column, $length) {
    return $this->addColumn('realBinary', $column, compact('length'));
});

Schema::create('table', function(Blueprint $table) {
    $table->realBinary('url_hash', 16);
});

1 Comment

Would you still say the same today?
4

Laravel author recommends to do a DB:statement call and run the raw SQL.

If you are running migration, you could run this raw SQL after Schema::create:

DB::statement('ALTER TABLE table_name ADD url_hash binary(16) AFTER some_column');

Depends on use case, you could need to run this raw SQL to drop the column before dropping the table:

DB::statement('ALTER TABLE table_name DROP url_hash');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.