Hello,

Today I'm going to teach you how to duplicate(clone) your posts/products/users (whatever you wish) in short tutorial.

 

First thing first:

Make method in any controller you like (controller naming is optional)

public function clonemaker($id)
{
      $product = Product::findOrFail($id);
      $newProduct = $product->replicate();
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
}

 

2- Make Route for your method:

Route::get('productsclone/{id}', '[email protected]')->name('productsclone');

As you see I passed {id} after my URL because I try to get my product base on id if you want to get it by slug or anything else you have to edit your controller method first.

 

3- Make button in blade

<a href="{{route('productsclone', $product->id)}}" class="btn-block btn btn-success"><i class="fa fa-clone"></i></a>

 

4- Test it, it's done laughing

 

Note:

Sometimes you might have unique columns in your posts/products database and with this method you will receive duplicated error.

How to fix it?

5- Change your controller method to something like this:

public function clonemaker($id)
{
      $product = Product::findOrFail($id);
      $title = $product->title;
      $newProduct = $product->replicate();
      $newProduct->title = str_before('cloned' .'_'. $title, 'dijd');
      $newProduct->save();

      return redirect()->route('products.index')
          ->with('info',
           'Product Cloned');
}

As you see I assumed that your title is unique column if it isn't change it to whatever column it is for you.

With this method your cloned product title will become something like: cloned_productxxxxx if you want to add after your title etc. read laravel helper documents.

PS: you can add more into this method if you have more than one unique column.

 

 

 

Let me know your opinion about this tutorial in comments wink

Share this article:

Comments