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
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();
});
}
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
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);
}
Please or to participate in this conversation.