gear
Image not found

Duplicate or Clone a database record with Laravel

Comment (0)

Admin


Have you ever needed to duplicate or clone a database record? Laravel provides a very handy function for this called replicate which will take an Eloquent model and make a copy so you can then make changes and save it.

Here's an example of how you might use this. Let's pretend you have a blog post and you want to make a copy of it to publish again. First grab the original model:

$post = Post::find(1);

Next, call the replicate method on it:

$newPost = $post->replicate(); 

Now, you can make any changes you need to the model and then resave it.

$newPost->created_at = Carbon::now();

$newPost->save();

All together it would look like this:

$post = Post::find(1);
$newPost = $post->replicate();
$newPost->created_at = Carbon::now();
$newPost->save();

 

if you want to add number with name follow this method

 

App\Models\Product

use App\Models\Product;

protected static function booted()
{
    static::creating(function ($product) {
        $originalName = $product->product_name;

        // Initialize variables
        $baseName = $originalName;
        $lastNumber = 2; // Default to 2 if no number found

        // Extract the base name and last number from the name, if any
        if (preg_match('/^(.*)-(\d+)$/', $originalName, $matches)) {
            $baseName = $matches[1];
            $lastNumber = intval($matches[2]);
        }

        // Generate a new name by incrementing the last number
        $newName = $baseName . '-' . $lastNumber;

        // Check if the new name already exists
        $count = Product::where('product_name', $newName)->count();
        while ($count > 0) {
            // If the new name exists, increment the number and check again
            $lastNumber++;
            $newName = $baseName . '-' . $lastNumber;
            $count = Product::where('product_name', $newName)->count();
        }

        // Set the product's name to the unique name
        $product->product_name = $newName;
    });
}

 

Example :

  • Product name
  • Product name - 2
  • Product name - 3
  • Product name -4

 

This replicate method is really helpful for quickly cloning or duplicating a database record.

Hope it will help.......

Thank you. 


Others Problem Fix Stroy



Comments (0)

Your Comment