2016-01-02 65 views
2

,而不必編寫使用:Laravel 5檢查對象是否存在,如果真

{{$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

你可以使用刀片的or語法:

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

不知道爲什麼你將其分配給$x,因此我將其刪除它,只是讀了,如果你確實需要它。

儘管如此,我個人認爲這是一種方法,無論對象是什麼型號的$data是一個實例。 :)

1

對於L5.1有pluck()

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

對於15.2有value()

{{ (int)$data->where(…)->value('quantity') }} 
+0

@limnote這給我:方法值不存在。 (View:C:\ wamp \ www \ brabiz \ resources \ views \ stock-sheet-1.blade.php) – imperium2335

2

第一件事 - 你不應該加載刀片內的數據。

在控制器,你應該做的:

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

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

現在在刀片文件

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

我不能這樣做,因爲視圖是靜態的。 – imperium2335