2017-01-30 77 views
1

我使用Laravel有兩個輸入文本形式:檢查數組爲空在PHP

<div class="col-md-6"> 
    <div class="form-group"> 
     {!! Form::label('price', 'Preço') !!} 
     <div class="input-group multi-control-group"> 
      <span class="input-group-addon">De</span> 
      {!! Form::text('price[]', null, ['class' => 'form-control']) !!} 
      <span class="input-group-addon">Até</span> 
      {!! Form::text('price[]', null, ['class' => 'form-control']) !!} 
     </div> 
    </div> 
</div> 

這是我的驗證功能:

if(!empty($request->year)) { 
    dd($request->year); 
} 

但是,如果沒有一套提交表單當值的數組驗證中爲空通過並顯示兩個位置沒有值。

array:2 [▼ 
    0 => "" 
    1 => "" 
] 

我想讓這個數組在驗證失敗。如何做這個驗證?

+0

您可以在所有元素上檢查「empty」,並且只有在其中至少有一個元素不爲空時才返回true。 – Antony

回答

0

即使空白,也會提交文本輸入。既然你把它們放在一個數組中,它們是空的元素,但仍然是阻止數組變爲空的元素。過濾掉空元素,然後檢查:

if(!empty(array_filter($request->year))) { 
    dd($request->year); 
} 

請注意,該字符串0將被過濾掉爲好。如果這是一個問題,那麼你需要一個替代方法,例如循環訪問數組並檢查""