dmSherazi dmSherazi - 5 months ago 10x
MySQL Question

Laravel 5 replicate() handle columns that have unique attribute

I am using laravel's

method of a Model to generate a copy of exiting instance. It works fine if there are no columns that are to be

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'];

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 ans name as nullables and then do something like this:

$product = Products::find(\Input::get('id'));
$newProduct = $product->replicate(['product_code', 'name']);
$newProduct->product_code = $product->product_code.'_'.$newProduct->id;
$newProduct->name = $product->name.'_'.$newProduct->id;

Of course you could wrap this into a function in case you do it in multiple places.