[英]Laravel livewire - any way to get live data from database?
[英]Is there any way to pass object as a parameter in laravel livewire?
我有一系列產品,我試圖將單個項目作為快速查看的參數傳遞,但我不能。 有人有任何解決方案嗎? 提前致謝。
@foreach ($products as $product)
@php
$product = (object) $product;
@endphp
<div class="col-md-3 mb-4">
<div class="product-item product-item-border custom-product-item">
<a class="product-item-thumb" href="shop-single-product.html">
@if (count($product->related_images) > 0)
<img src="{{ $product->related_images[0]['image'] }}" width="233" height="245" alt="Image-HasTech">
@endif
</a>
<div class="product-item-action">
<button type="button" class="product-action-btn action-btn-wishlist" data-bs-toggle="modal" data-bs-target="#action-WishlistModal">
<i class="icon-heart"></i>
</button>
<button type="button" class="product-action-btn action-btn-compare" data-bs-toggle="modal" data-bs-target="#action-CompareModal">
<i class="icon-shuffle"></i>
</button>
<button type="button" wire:click="quickView({{ $product }})" class="product-action-btn action-btn-quick-view">
<i class="icon-magnifier"></i>
</button>
</div>
<div class="product-bottom">
<div class="product-item-info text-center pb-6">
<h5 class="product-item-title mb-2"><a href="shop-single-product.html">{{ $product->product_name }}</a></h5>
{{-- <div class="product-item-price mb-0">{{ $product->default_price }}<span class="price-old">{{ $product->default_price }}</span></div> --}}
</div>
<div class="d-flex justify-content-between">
<div class="ms-4 product-item-price mb-4">{{ $product->default_price }}</div>
<button type="button" wire:click="addToCart({!! $product->id !!})" class="info-btn-cart me-4 mb-4"><i class="icon-handbag"></i></button>
</div>
</div>
</div>
</div>
@endforeach
<div class="col-12">
<div class="text-center">
<div wire:click="nextPage" type="button" class="btn btn-primary">Load more</div>
</div>
</div>
在我的 controller 中,我正在嘗試做這樣的事情:
public function quickView($product)
{
$this->view_product = $product;
}
我試圖傳遞 object 但我收到這樣的錯誤: htmlspecialchars() expects parameter 1 to be string, object given
發生錯誤是因為在 blade {{ }}
中會自動轉義 output。而這個 function 只會轉義字符串。
相反,你可以做的是
wire:click="quickView( {{ $product->id }} )
在你的 livewire 組件中
public function quickView($product_id)
{
// I assume $products is collection
$this->view_product = $this->products->where('id', $product_id)->first();
}
編輯:
如果您不想在 quickView() 中添加“額外查詢”
我建議您更改 $products 集合的收集方式
$this->products = $existing_query->get()->keyBy('id');
這將生成 object 產品的數組列表。
之后在 quickView() 中執行以下操作
public function quickView($product_id)
{
$this->view_product = $this->products[$product_id];
}
額外注意:如果找不到具有所選 ID 的產品,請添加某種檢查或驗證
可能有點太晚了,但我必須通過鍵入提示 object class 來解決類似的問題。來自文檔
所以也許你可以這樣做:
public function quickView(Product $product)
{
$this->view_product = $product;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.