
Hello,
Today I'm going to teach you how to duplicate(clone) your posts/products/users (whatever you wish) in short tutorial.
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}', 'ProductController@clonemaker')->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
4- Test it, it's done
Note:
Sometimes you might have unique
columns in your posts/products database and with this method you will duplicated error.
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.
- Last updated 5 years ago
Be the first to leave a comment.
You must login to leave a comment