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.
Recently ran into this issue, most efficient and effective was just to use unix time stamp. Here is another example to give you a better idea of what is going on without having to null fields and such.
$page = Page::find($id);
$duplicatePage = $page->replicate();
$duplicatePage->name = 'Copy of ' . $page->name;
$duplicatePage->slug = $page->slug . '-' . time();
$duplicatePage->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With