【问题标题】:laravel 5.4 convert collection of eloquent object to integerlaravel 5.4将雄辩对象的集合转换为整数
【发布时间】:2017-10-24 16:55:18
【问题描述】:

当我尝试将对象集合与整数进行比较时..here

@if($in_closet == $product->id )
                <li><a id="add_closet" href="{{ route('user.addtocloset', ['id' => $product->id]) }}"><i class="fa fa-archive" aria-hidden="true"></i> Add to closet</a></li>
                @else
                <li><a id="my_closet" href="{{ route('closet') }}"><i class="fa fa-archive" aria-hidden="true"></i> My Closet</a></li>
                @endif

$in_closet 变量中,当我尝试与具有整数值的$product-&gt;id 进行比较时,我正在收集类似 [50,52,53,54] 的对象,它向我显示此错误

类 Illuminate\Support\Collection 的对象无法转换 到int

这是在我的控制器变量中

   $in_closet = ProductCloset::where('closet_id',$user->id)->pluck('product_id');

我现在找到了问题,但是我的问题是如何解决它我真正需要的是,如果产品 ID 等于该集合对象中的任何产品 ID,则显示一个 div,否则显示另一个 div..

我想知道如何将集合对象与整数进行比较,或者我是如何实现这一点的..请任何人帮助找到解决此问题的方法

【问题讨论】:

    标签: php arrays laravel object


    【解决方案1】:

    您正在尝试将 Collection 对象与整数进行比较。如果您想知道$product-&gt;id 是否在$in_closet 中,您应该使用您可以使用的contains() 方法。查看更多here

    所以,$in_closet 是一个集合,你可以检查它是否包含特定元素,如下所示:

    if($in_closet->contains($product->id))
    {
        // it contains the element
    }
    

    【讨论】:

    • 谢谢 Mozammil,我得到了确切的答案,非常感谢
    • 太棒了。如果它对你有帮助,你能接受这个答案吗? @Karthiga
    猜你喜欢
    • 2019-05-31
    • 2021-09-07
    • 1970-01-01
    • 2015-03-04
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多