I am using laravel's replicate()
method of a Model to generate a copy of exiting instance. It works fine if there are no columns that are to be unique
In my case there are some columns that are to be unique so I use this
$pr = Products::find(\Input::get('id'))->replicate();
$pr['product_code'] = $pr->product_code . '_'.$pr['id'];
$pr['name'] = $pr->name . '_'.$pr['id'];
$pr->save();
This will make sure that if a product is replicated once it will handle the unique column problem. But if the product is replicated again it will cause the problem again.
How I can I solve this issue
I would set in database product_code
and name
as nullables and then do something like this:
$product = Products::find(\Input::get('id'));
$newProduct = $product->replicate(['product_code', 'name']);
$newProduct->save();
$newProduct->product_code = $product->product_code.'_'.$newProduct->id;
$newProduct->name = $product->name.'_'.$newProduct->id;
$newProduct->save();
Of course you could wrap this into a function in case you do it in multiple places.