Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rorymcdaniel's avatar

Migration column modifiers

I was looking at the documentation for migrations this morning and I noticed the ->storedAs($expression) and ->virtualAs($expression) but I can't seem to find any other reference as to how these might be used.

Does anybody have any examples of how to use these? I can see how they could be useful, but I'm not exactly sure what my expression would look like.

0 likes
1 reply
willvincent's avatar

As I understand it, these are for defining "generated columns" which, are only available in Mysql 5.7.5+ (not compatible with postgres, sqlite, etc as far as I am aware).

So, suppose you wanted to achieve the following:

CREATE TABLE sales ( 
    -> name VARCHAR(20),  
    -> price_eur DOUBLE,
    -> amount INT,
    -> total_eur DOUBLE AS (price_eur * amount),
    -> total_usd DOUBLE AS (total_eur * xrate),
    -> xrate DOUBLE);

You would define it much as it is done in that SQL query...

Schema::create('sales', function (Blueprint $table) {
  $table->string('name');
  $table->double('price_eur');
  $table->integer('amount');
  $table->double('total_eur')->storedAs('price_eur * amount');
  $table->double('total_usd')->storedAs('total_eur * xrate');
  $table->double('xrate');
});

Difference between stored and virtual is that virtual are calculated on the fly, and stored are calculated at insert/update. Also only stored generated columns can be part of an index.

Relevant mysql docs: http://mysqlserverteam.com/generated-columns-in-mysql-5-7-5/

2 likes

Please or to participate in this conversation.