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

Alinush's avatar

How to set a function as default in migration

How to set a function as default in migration? For example I use the code bellow: $table->uuid('ID')->default('newid()'); I am using MS SQL database and I need to autogenerate the uuid itself, but when I run the migration the default will be a string not the function and If I remove the quotation marks then I got the error at migration. The problem is that I have a lot of tables which needs the autogenerate function as default.

0 likes
4 replies
tykus's avatar

Probably needs to be sent raw:

 $table->uuid('ID')->default(DB::raw('newid()'));
Alinush's avatar

Unfortunately is the same thing. When I check the database is in the same format with quotation marks. I need to be sent without quotation marks.

kylemilloy's avatar

I've achieved this by modifying the boot function on the Eloquent Model.


class MyModel extends Model
{
    protected static function boot()
    {
        parent::boot();
    
        static::creating(function($myModel) {
            $myModel->id = function() {
                // return some value here.
            }
        }
    }
}

If you're replacing the $table->increments('id') bit from your migration and relying on just a uuid or something then I'd suggest you also add public $incrementing = false to the model

Snapey's avatar

you cannot embed a function in the design if the database.

Please or to participate in this conversation.