Back

Virtual Column In Laravel

Setting virtual column from your existing JSON column

Virtual columns are not physically stored in the database but are calculated on-the-fly. They are particularly useful when working with JSON columns, as they allow you to extract and utilize data without duplicating it.


Laravel Migration File

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->json('meta')->nullable();
    $table->string('author_id')->nullable()->virtualAs("json_unquote(json_extract(meta, '$.author_id'))");
    $table->string('slug')->nullable()->virtualAs("json_unquote(json_extract(meta, '$.slug'))");
});

These virtual columns do not take up extra storage space but are accessible as part of queries.

Table Structure

idmetaauthor_idslug
1{“author_id”: “12345”, “slug”: “my-first-post”}12345my-first-post

By using virtual columns, author_id and slug are extracted dynamically from the JSON column meta.

Kuala Lumpur, Malaysia.
© Copyright 2025. All rights reserved.