1

I have a db table with a JSON column. I now want to add an index to parts of that json.

It turns out you can only add an index on a json column when creating the table.

Here's what I tried in a migration:

DB::statement(DB::raw(<<<SQL
CREATE TABLE area_groups (
  title JSON, 
  `created_at` timestamp null, 
  `updated_at` timestamp null, 
  INDEX area_groups_title_de (
    (
      JSON_VALUE(title, '$.de')
    )
  ), 
  INDEX area_groups_title_en (
    (
      JSON_VALUE(title, '$.en')
    )
  )
) default character set utf8mb4 collate 'utf8mb4_unicode_ci'
SQL
));

Schema::table('area_groups', function (Blueprint $table) {
    $table->id()->change();
    $table->foreignId('area_id')->change()->constrained();
});

My idea was to create the json column and indexes in a raw db statement and do the rest with Laravel's migration helpers.

Creating the table seems to work, but running this migration fails with the following error message:

Argument 1 passed to Doctrine\DBAL\Schema\Index::_addColumn() must be of the type string, null given, called in vendor/doctrine/dbal/src/Schema/Index.php on line 72
6
  • Where exactly does it say that this works only when creating a table? Commented Nov 15, 2021 at 10:30
  • @Alex Doing something like create index area_groups_title_de on area_groups(JSON_VALUE(title, '$.de')); gives me a mysql syntax error. Commented Nov 15, 2021 at 10:31
  • And the mysql docs on json indexes only mention create table Commented Nov 15, 2021 at 10:31
  • Are you sure you're using a mysql version that supports what you're trying to do? Also, I don't think you need DB::raw inside DB::statement. Commented Nov 15, 2021 at 12:56
  • @IGP yes, when I run that create table statement manually on a console it works. Commented Nov 16, 2021 at 7:21

1 Answer 1

-2

you can use json_encode(['id' => 1, 'name' => 'User 1']);

Laravel Schema does support JSON field types as well.

You can use text field type as well to store JSON data.

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

1 Comment

I'm looking for a way to add a mysql index to a column in my json column, not for a way to encode json.

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.