2017-04-09 135 views
2

我試圖寫一個if-else循環:如果有一個嵌入保存在數據庫中,它應該顯示一個日曆,如果不是,它應該顯示一個按鈕,說「添加新日曆/添加新的嵌入「,但它不起作用。我無法弄清楚爲什麼。當存在保存在數據庫中的嵌入它顯示嵌入但是,如果沒有它不顯示按鈕來添加一個新的日曆/嵌入的嵌入:laravel - if else loop not working proper

刀片視圖:

@if (empty($calendars)) 

@else 
    <h4>No calendar settings</h4><br> 
    <a href="{{ route('calendarsettings.create')}}"> 
     <button class="btn btn-success btn-cons m-b-10" type="button"> 
      <i class="fa fa-cloud-upload"></i> 
      <span class="bold">Add embed</span> 
     </button> 
    </a> 
@endif 
@foreach($calendars as $calendar) 
    {{ $calendar->embed }} 
@endforeach 

控制器:

public function kalendarz() { 
    $calendars = Calendar::with('users')->where('user_id', Auth::user()->id)->get(); 
    return view('kalendarz',['calendars'=>$calendars]); 
} 
+0

刀片代碼塊告訴「如果沒有日曆什麼都不做」 –

回答

0

在Laravel 5.4,我可能會使用@unless刀片指令,將顯示該塊,除非條件得到滿足。下面的代碼會達到什麼效果:「如果我們有一些條目,則顯示條目,並且除非我們有條目才顯示按鈕」。

@if($calendar) 
    // show entries 
@endif 

@unless(empty($calendars)) 
    // show a button to add a new one 
@endunless 

它種是相同的「邏輯」與其他人,但不知何故,我覺得它更清晰,便於比@else語句來讀,並使其與分離是否。

1

正確的語法是:

@if(empty($calendars)) 
    <h4>No calendar settings</h4></br> 
    <a href="{{ route('calendarsettings.create')}}"> 
     <button class="btn btn-success btn-cons m-b-10" type="button"><i class="fa fa-cloud-upload"></i> <span class="bold">Add embed</span></button> 
    </a> 
@else 
    @foreach($calendars as $calendar) 
     {{ $calendar->embed }} 
    @endforeach 
@endif 
+0

如果沒有日曆,那麼它仍然沒有。在數據庫中嵌入文本字段 – tomczas

+0

@tomczas請顯示'{{dd($ calendars)}}' –

+0

的結果它什麼也沒有顯示 – tomczas

0

empty()樂趣ctions清空變量$calendars,所以儘量使用count()

@if(count($calendars) > 0) 
    <h4>No calendar settings</h4></br> 
    <a href="{{ route('calendarsettings.create')}}"> 
     <button class="btn btn-success btn-cons m-b-10" type="button"><i class="fa fa-cloud-upload"></i> <span class="bold">Add embed</span></button> 
    </a> 
@else 
    @foreach($calendars as $calendar) 
     {{ $calendar->embed }} 
    @endforeach 
@endif 
+0

還是什麼都沒有。不工作 – tomczas

0

當使用Eloquent擺脫你的Illuminate\Database\Eloquent\Collection實例的數據庫的結果。要檢查該集合是否爲空,請使用$collection->isEmpty()$collection->isNotEmpty()(L5.4)。

@if ($calendars->isNotEmpty()) 
    // Have entries. 
@else 
<h4>No calendar settings</h4></br> 
<a href="{{ route('calendarsettings.create')}}"><button class="btn btn-success btn-cons m-b-10" type="button"><i class="fa fa-cloud-upload"></i> <span class="bold">Add embed</span> 
    </button></a> 
@endif 

@foreach($calendars as $calendar) 
    {{$calendar->embed}} 
@endforeach 
+0

仍然沒有。不工作 – tomczas