Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Created September 30, 2022 22:00
Show Gist options
  • Save DominikStyp/5ae6bbf734338e8cb893b99aa4f38af2 to your computer and use it in GitHub Desktop.
Save DominikStyp/5ae6bbf734338e8cb893b99aa4f38af2 to your computer and use it in GitHub Desktop.
Laravel: virtualAs(), virtual column extracted from JSON field
<?php
class SomeMigration {
public function up() {
Schema::table('json_data', function(Blueprint $table) {
$table->string('email', 100)
// here we deine the virtual column for the json_data table which will be just a column view
->virtualAs("json_unquote(json_extract(json, '$.email'))");
// here we can define index for that column
->index();
});
}
}
<?php
// tinker
>>> DB::table('json_data')->select('json->email')->debug();
// output
>>> select json_unquote(json_extract(json, '$.email')) from json_data;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment