Pars
Pars

Reputation: 5272

Select, Modify and Insert result as new record in Laravel

How can I force laravel to always create new record when I use save() method or use separated calls like create or update.
for example, I want to get some records from a table, modify them and save them as new records.

$products = Product::where('category_id', 10)->get();

foreach( $products as $product ){
    $product->name = 'new name';
    $product->save();
}

above script, update records, in phalconphp I can be specific and say $product->create() and new record will create.

Is this possible in Laravel?

Upvotes: 1

Views: 448

Answers (3)

Bogdan
Bogdan

Reputation: 44586

Here's a simpler approach for cloning a model using replicate:

$products = Product::where('category_id', 10)->get();

foreach( $products as $product )
{
    // Clone the model
    $clone = $product->replicate();

    // Apply any changes you want to the cloned model
    $clone->name = 'new name';
    // ...

    // Save the cloned/modified model as a different record
    $clone->save();
}

Upvotes: 4

geoandri
geoandri

Reputation: 2428

Maybe you need something like the following? Create a new product and either you set its attributes from an existing one or assign a new value.

 $products = Product::where('category_id', 10)->get();

 foreach( $products as $product ){       

 $newproduct = new Product;
 $newproduct ->name = $product->name;  // or assign a new value
 $newproduct ->attribute1 = $product->attribute1; // or assign a new value
 $newproduct ->attribute2 = $product->attribute2;// or assign a new value
 $newproduct ->attribute3 = $product->attribute3;// or assign a new value
 $newproduct ->save();
 }

Upvotes: 0

Ceeee
Ceeee

Reputation: 1442

why not...

$products = Product::where('category_id', 10)->get();

foreach( $products as $product ){
    $new_product = new Product();
    $new_product->name = 'new name';
    $new_product->other_column = $product->other_column;
    $new_product->save();
}

Upvotes: 1

Related Questions