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

kuns25's avatar

How do I concatenate a String with id and save in Database

Hii , I've created one form Saving Names & ids in Database , but i also want to save manual Id related to unique Id in Database ,

For Example ,

In Database I'm Saving Name : Jack Dawson & (unique) Id = 1 ,

now i want to add manual id For. RGG01 , how do i prefix this 'RGG' in Controller or concatenate this 'RGG' string with 'Id' .

Thanks in Advance

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

You can use the created model event to retrieve the id assigned to the newly created model, then build your manual id and save the model again.

// YourModel.php

public static function boot()
{
    static::created(function ($model) {
        $model->manual_key = 'RGG' . str_pad($model->id, 2,'0',STR_PAD_LEFT);
        $model->save();
    });
}
kuns25's avatar

I've Pasted above code in my model , but what should i write in my controller , i'm getting below error

SQLSTATE[HY000]: General error: 1364 Field 'manual_key' doesn't have a default value

Tray2's avatar

I would probaly use a mutator for that.

migration

            $table->increments('id');
            $table->string('name');
            $table->string('identifier');
            $table->timestamps();

model


public function setIdentifierAttribute($value)
{
    $this->attribute['identifier'] = 'RGG' . str_pad($value, 2,'0',STR_PAD_LEFT);
}
1 like

Please or to participate in this conversation.