【问题标题】:Livewire add an quantity input for each rowLivewire 为每一行添加一个数量输入
【发布时间】:2022-02-15 11:15:41
【问题描述】:

我正在尝试从产品列表中将产品添加到我的购物车。我正在使用 Laravel Livewire。使用下面的代码,我设法将单击订单的每个产品添加到购物车(这只是一个会话变量)。现在,我正在尝试添加数量输入,以便为每种产品选择要添加到购物车的产品数量。

从我下面的代码中请记住,Products 是一个雄辩的集合,在该集合中我没有属性数量。在我看来,这也不是必需的,因为数量不是产品模型的一部分,而是属于我的购物车的东西。

下面是我的 Livewire php 部分。

class Dashboard extends Component
{
    use WithPagination;

    public string $search = '';

    public function render(): View 
    {
        return view('welcome', [
            'products' => Product::search('description', $this->search)->paginate(9)
        ])->layout('layouts.app');
    }

    public function addToCart(int $productId)
    {
        Cart::add(Product::where('id', $productId)->first());
    }

}

这是刀片部分:

 @foreach($products as $product)
    <x-table.row wire:loading.class.delay="opacity-50" wire:key="{{ $product->id }}"> 
      <x-table.cell>{{ $product->description }}</x-table.cell>
      <x-table.cell> &euro;{{ number_format($product->price, 2) }}</x-table.cell>
       <x-table.cell> 
        <input type="number"name="quanity" class="w-16 mx-8" />
          <button wire:click="addToCart({{$product->id}})">Order</button>
       </x-table.cell>
      </x-table.row>
 @endforeach

我认为最好的选择是向addToCart 函数添加第二个参数,即数量。但我做不到。

非常欢迎提出建议。

谢谢。

【问题讨论】:

  • 看来你需要在你的livewire类中为你的数量设置一个数组,可能用产品id作为数组键,数量作为值,wire:model绑定你的@987654326 @ 这个数组的输入字段。我现在没有时间玩这个,但我认为这是可行的。

标签: php laravel laravel-livewire alpine.js


【解决方案1】:

这样的事情可能就足够了

public function addToCart(int $productId, int $quantity)
    {
        Cart::add(Product::where('id', $productId)->first()->setAttribute('quantity',  $quantity));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多