Laravel – Eloquent virtual column

작성자

카테고리:

← 피드로
DEV Community · Mubashar Ahmad · 2026-07-08 개발(SW)

Mubashar Ahmad

Save additional data to virtual column

Installation

composer require zanysoft/virtualcolumn

Enter fullscreen mode Exit fullscreen mode

Usage

Use the VirtualColumn trait on your model:

use Illuminate\Database\Eloquent\Model;
use ZanySoft\VirtualColumn\VirtualColumn;

class MyModel extends Model
{
    use VirtualColumn;

    public $guarded = [];
}

Enter fullscreen mode Exit fullscreen mode

For custom virtual column where you want to save additional data. Default column name is data

use Illuminate\Database\Eloquent\Model;
use ZanySoft\VirtualColumn\VirtualColumn;

class MyModel extends Model
{
    use VirtualColumn;

    public static function getDataColumn(): string
    {
        return 'data'; //name of the column that stores additional data.
    }
}

Enter fullscreen mode Exit fullscreen mode

For saving data to existing database columns, by default all columns from the table are selected, except virtual column.

use Illuminate\Database\Eloquent\Model;
use ZanySoft\VirtualColumn\VirtualColumn;

class MyModel extends Model
{
    use VirtualColumn;

    public static function getCustomColumns(): array
    {
        return [
            'id',
            'custom1',
            'custom2',
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

Create a migration:

public function up()
{
    Schema::create('my_models', function (Blueprint $table) {
        $table->increments('id');

        $table->string('custom1')->nullable();
        $table->string('custom2')->nullable();

        $table->json('data');
    });
}

Enter fullscreen mode Exit fullscreen mode

And store any data on your model:

$myModel = MyModel::create(['custom1' => 'custom 1', 'custom2' => 'custom 2', 'foo' => 'bar']);
$myModel->update(['custom1' => 'custom 1', 'custom2' => 'custom 2', 'foo' => 'bar']);

Enter fullscreen mode Exit fullscreen mode

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다