0

I want to save the same data with 365 records within one table.

I've tried with replicate(), but was unsuccessful. I tried this on the Apache server and used Laravel 5.7.

My controller

public function price_save(Request $request) {
  $price = new Price();
  $price->price = $request->price;
  $price->extra_bed = $request->extra_bed;
  $price->room_id = $request->room;
  $id = $request->room;
  $price = Price::find($id);

  if(null !== $price) {
    $new = $price->replicate();

  if(null !== $new) {
    $new->push();
  // $price->save();
}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dora
  • 1
  • 2

2 Answers2

0

I am NOT sure about your code, But you can customize it as per your needs, To just get idea :

$model = User::find($id);

$model->load('invoices');

$newModel = $model->replicate();
$newModel->push();


foreach($model->getRelations() as $relation => $items){
    foreach($items as $item){
        unset($item->id);
        $newModel->{$relation}()->create($item->toArray());
    }
}

Credits

0
public function price_save(Request $request, int $id)
{
    if ($id > 365) {
        return;
    }
    $price = new Price();
    $price->price = $request->price;
    $price->extra_bed = $request->extra_bed;
    $price->room_id = $request->room;
    $price->save();
    $existing = Price::find($request->room); 
    if ($existing) {
        $request = $request->replace([
            'price' => $price->price,
            'extra_bed' => $price->extra_bed,
            'room_id' => $price->room,
        ]);
    }
    return price_save($request, $id++);
}
ThePigeon
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 15 '22 at 15:36