Как суммировать данные каждой строки в динамическом поле ввода Laravel Livewire

У меня есть ввод с динамическим полем, поэтому я могу добавить больше столбцов и удалить их. В этом вводе у меня есть столбец total_price, по цене мне нужна цена * кол-во. Но я не знаю, как это сделать при множественном входе. Я просто могу сделать это на одном входе. Моя форма и livewire такие:

  1. форма

       <form>
         <button wire:click.prevent="add({{$i}})">
         Add 
         </button>
    
         <input type="hidden" wire:model="newid.0">
    
         <input wire:model="nama_barang.0" type="text" />
         <input wire:model="qtt.0" type="text" />
         <input wire:model="price.0" type="text" />
         <input wire:model="qty.0" type="text" /> 
         <input wire:model="total_price" type="text" /> // here the problem
    
         @foreach($inputs as $key => $value)
         <input wire:model="nama_barang.{{ $value }}" type="text" />
         <input wire:model="qtt.{{ $value }}" type="text" />
         <input wire:model="price.{{ $value }}" type="text" />
         <input wire:model="qty.{{ $value }}" type="text" /> 
         <input wire:model="total_price" type="text" /> // on here i get the problem
    
         @endforeach
    
         <button wire:click.prevent="store()">Submit</button>
     </form>
    

и это мой livewire

public $belanja_id, $nama_barang, $qtt,$newid;
public $updateMode = false;
public $inputs = [];
public $i = 1;
public $total_price ;
public $price= [] ;
public $qty = [];

public function add($i)
{
    $i = $i + 1;
    $this->i = $i;
    array_push($this->inputs ,$i);
}

public function mount($id)
{
   $belanja = $this->belanja = Belanja::findOrFail($id);
   $this->newid = $belanja->id;
   $this->k_uraian = $belanja->uraian;

} 

public function remove($i)
{
    unset($this->inputs[$i]);
}

public function render()
{
    $this->total_price =array_sum($this->price) * array_sum($this->qty)   ; // i try with this but only get 1 rows , can someone help ?
    
    return view('livewire.input-belanja-lw');
}

и вы можете увидеть мою форму на этом изображении (лучше посмотрите это изображение, чтобы узнать мою проблему), я не могу добавить сумму total_price. так может кто-нибудь помочь с этим?

мои ссылки взяты с этого сайта site

ОБНОВИТЬ . теперь мой ввод правильный, но в моем магазине есть ошибка e

это моя функция магазина

 public function store()
{
    

    foreach ($this->nama_barang as $key => $value) {
       $bel = AnakBelanja::create([
            'belanja_id' => $this->newid,
            'nama_barang' => $this->nama_barang[$key], 
            'qtt' => $this->qtt[$key],
            'price' => $this->price[$key],
            'qty' => $this->qty[$key]
            ]);        
    }

    $this->inputs = [];

    $this->resetInputFields();


    return redirect()->route('detail', $bel->belanja_id);

    $this->emit('alert', ['type' => 'success', 'message' =>'Succes Melakukan Input / Update']);

}

person Adhik Mulat    schedule 22.10.2020    source источник


Ответы (1)


так как вы это делаете, это невозможно, поэтому я сделал несколько исправлений, попробуйте это

Составная часть

public $belanja_id, $nama_barang, $qtt, $newid;
public $updateMode = false;
public $inputs = [
    [
        "newid" => "",
        "nama_barang" => "",
        "qtt" => "",
        "price" => "",
        "qty" => "",
        "total_price" => "",
    ]
];

public function render()
{
    return view('livewire.input-belanja-lw');
}

public function add()
{
    array_push($this->inputs, [
        "newid" => "",
        "nama_barang" => "",
        "qtt" => "",
        "price" => "",
        "qty" => "",
        "total_price" => "",
    ]);
}

public function mount($id)
{
    $belanja = $this->belanja = Belanja::findOrFail($id);
    $this->newid = $belanja->id;
    $this->k_uraian = $belanja->uraian;
}

public function remove($i)
{
    unset($this->inputs[$i]);
}

Лезвие

<form>
    <button wire:click.prevent="add()">
        Add
    </button>

    @foreach($inputs as $key => $value)
    <input type="hidden" wire:model="inputs.{{ $key }}.newid" value="{{ $key }}">
    <input wire:model="inputs.{{ $key }}.nama_barang" type="text" />
    <input wire:model="inputs.{{ $key }}.qtt" type="text" />
    <input wire:model="inputs.{{ $key }}.price" type="text" />
    <input wire:model="inputs.{{ $key }}.qty" type="text" />
    <input value="{{ (int)$value['price'] * (int)$value['qty']  }}" type="text" />
    <br>
    @endforeach

    <button wire:click.prevent="store()">Submit</button>
</form>
person Kamlesh Paul    schedule 22.10.2020
comment
подожди, я попробую - person Adhik Mulat; 22.10.2020
comment
хорошо, его работа, сэр, могу я задать еще 1 вопрос ?? как я могу суммировать все это total_price? так я могу показать общую сумму total_price? - person Adhik Mulat; 22.10.2020
comment
у меня проблема в магазине. это ошибка Недопустимый аргумент для foreach () - person Adhik Mulat; 22.10.2020
comment
в вашем магазине от $this->nama_barang as $key до $this->inputs as $key должно быть так, я думаю - person Kamlesh Paul; 22.10.2020
comment
получить ошибку Попытка получить доступ к смещению массива для значения типа null - person Adhik Mulat; 22.10.2020