简体   繁体   English

试图弄清楚为什么我的foreach导入不起作用

[英]Trying to figure out why my foreach import doesnt work

I've on my view: 我的观点是:

@foreach($cart_item->where('shopping_cart_id','37') as $cart) 

 <li class="clearfix">{{$cart->prize_id}}</li>

@endforeach

Can somebody help me figure out whats wrong with my foreach loop? 有人可以帮我弄清楚我的foreach循环有什么问题吗?

I have come down to just trying to basically displaying the id's but its giving me an php error. 我已经下来试图基本上显示id,但它给我一个PHP错误。

"Undefined variable cart_item", but I did define the variable on the cart controller as so: “未定义的变量cart_item”,但我确实在购物车控制器上定义了变量:

$cart_item = ShoppingCartItem::where('shopping_cart_id',$cookie->cart_id)->where('prize_id',$_POST['prize_id'])->first();

Based on your edited question, the solution is to pass $cart_item to your view. 根据您编辑的问题,解决方案是将$cart_item传递给您的视图。

Once that is done, you can just do the following: 完成后,您可以执行以下操作:

@foreach($cart_item as $cart)

What you are currently doing is not the recommended way of doing it. 您目前正在做的不是推荐的做法。 This logic should be in your Controller and not your View. 此逻辑应位于Controller中,而不是View中。

You have to pass that variable to the view. 您必须将该变量传递给视图。 I guess it's Laravel so just when calling your view add it to the comapct function 我猜这是Laravel所以只是在调用你的视图时将它添加到comapct函数中

view('viewname', compact('cart_item'))

And like other suggested don't do it that way, it's better do define a scope function in that model that does it for you. 和其他建议不要那样做,最好在该模型中定义一个范围函数来为您完成。

At first you are adding controller logic on a view, and that is really a bad practice. 首先,您在视图上添加控制器逻辑,这实际上是一种不好的做法。

Your problem looks like on your controller line: 你的问题在你的控制器行上看起来像:

$cart_item = ShoppingCartItem::where('shopping_cart_id',$cookie->cart_id)->where('prize_id',$_POST['prize_id'])->first();

Is returning NULL, it means the ShoppingCartItem is not found on your query or you are just not sending the variable to the view. 返回NULL,表示在查询中找不到ShoppingCartItem,或者您只是没有将变量发送到视图。

In your view you can control if the $cart_item variable exists like this: 在您的视图中,您可以控制$ cart_item变量是否存在,如下所示:

@if(isset($cart_item))
  @foreach($cart_item->where('shopping_cart_id','37') as $cart) 

   <li class="clearfix">{{$cart->prize_id}}</li>

 @endforeach
@endif

This will prevent future errors in case the $cart_item variable is not set. 如果未设置$ cart_item变量,这将防止将来出现错误。

I think You should do like this 我想你应该这样做

$cart_item = ShoppingCartItem::where('shopping_cart_id',$cookie->cart_id)->where('prize_id',$_POST['prize_id'])where('shopping_cart_id','37')->get();

and after that use it in your view 然后在你的视图中使用它

@foreach($cart_item as $cart) 

 <li class="clearfix">{{$cart->prize_id}}</li>

@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM