Laravel 5 检查对象是否存在,如果为真则使用
Laravel 5 check if object exists and use if true
不必写:
{{$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}}
有没有更简洁的方法?
对于 L5.1 有 pluck():
{{ (int)$data->where(…)->pluck('quantity') }}
对于 L5.2 有 value():
{{ (int)$data->where(…)->value('quantity') }}
您可以使用 Blade 的 or
语法:
{{ $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first->quantity or 0 }}
不确定为什么要将它分配给 $x
,所以我删除了它,如果您确实需要它,请重新阅读。
不过,就我个人而言,无论 $data
对象是哪个模型的实例,我都会将其作为一个方法。 :)
第一件事 - 你不应该在 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 }}
不必写:
{{$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}}
有没有更简洁的方法?
对于 L5.1 有 pluck():
{{ (int)$data->where(…)->pluck('quantity') }}
对于 L5.2 有 value():
{{ (int)$data->where(…)->value('quantity') }}
您可以使用 Blade 的 or
语法:
{{ $data->where('colour_id', 1)->where('size_id', 1)->where('product_id', 1)->first->quantity or 0 }}
不确定为什么要将它分配给 $x
,所以我删除了它,如果您确实需要它,请重新阅读。
不过,就我个人而言,无论 $data
对象是哪个模型的实例,我都会将其作为一个方法。 :)
第一件事 - 你不应该在 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 }}