![](/img/trans.png)
[英]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.