Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 replicate() handle columns that have unique attribute

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

like image 912
dmSherazi Avatar asked Oct 28 '25 04:10

dmSherazi


2 Answers

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.

like image 138
Marcin Nabiałek Avatar answered Oct 29 '25 17:10

Marcin Nabiałek


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();
like image 29
Charl Kruger Avatar answered Oct 29 '25 17:10

Charl Kruger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!