Laravel 5检查对象是否存在,如果为true则使用

时间:2016-01-02 12:59:57

标签: php laravel object laravel-5 blade

而不是写:

{{$x = $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first() ? $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first()->quantity : 0}}

有更清洁的方式吗?

3 个答案:

答案 0 :(得分:3)

您可以使用Blade or语法:

{{ $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first->quantity or 0 }}

不确定为什么要将其分配给$x,所以我将其删除了,只要你确实需要就读了。

但就个人而言,我会在$data对象是其实例的任何模型上使其成为一种方法。 :)

答案 1 :(得分:2)

首先 - 你不应该在Blade中加载数据。

在控制器中你应该这样做:

$product = $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first();

return view('sample.blade.php', compact('product'));

现在在你的Blade文件中

{{ $product ? $product->quantity : 0 }}

答案 2 :(得分:1)

对于L5.1,pluck()

{{ (int)$data->where(…)->pluck('quantity') }}

对于L5.2,有value()

{{ (int)$data->where(…)->value('quantity') }}
相关问题