2016-11-20 115 views
2

我正在使用Laravel 5.3。我的第一個Laravel項目/學習經驗 在我的刀片文件中,我使用以下片段在PUT或POST請求之後的字段下顯示錯誤。

在這種情況下,數據庫字段稱爲的firstName

 @if ($errors->has('firstName')) 
      <span class="help-block"> 
       <strong>{{ $errors->first('firstName') }}</strong> 
      </span> 
     @endif 

現在,因爲我有很多領域,我必須保持repeatings這個塊各個領域。我擡頭看了看Laravel文檔上的刀片模板(延伸的葉片部分),我想我可以做的AppServiceProvider類(AppServiceProvider .PHP)

public function boot() 
{ 
    // 
    Blade::directive('showIfError', function($fieldName) { 
     if ($errors->has('$fieldName')) { 
      echo "<span class='help-block'> 
      <strong> $errors->first('$fieldName') </strong> 
      </span>"; 
     } 
    }); 
} 

然後用

@showIfError(「的firstName」以下)

,但沒有運氣......我得到的錯誤「未定義的變量:錯誤」

看起來像Laravel錯誤收集在圖中沒有文件訪問。

感謝任何幫助。謝謝。

+0

你可以請包括你想達到什麼嗎? – Abrar

+0

我不想複製和粘貼我的表單中每個字段的if(errors ...)塊。相反,我想要一個像@showIfError('fieldName')這樣的宏/刀片模板,並且最終輸出將像上面給出的跨度塊一樣呈現。 –

+0

我發現視圖緩存干擾了輸出。如果我刪除存儲(緩存)文件夾中的所有文件,我可以使用會話('錯誤')工作,但它只能運行一次!再次使用相同的錯誤提交表單不會產生任何輸出!因此,我無法完全測試任何答案是否可行:-( 另外,Blade :: directive函數不需要2個參數。 –

回答

1

事情是$errors在封閉無法訪問。此外,由於指令閉包只接受字符串,因此無法傳遞整個對象。使用簡單的數據,你可以implode(),然後explode()它,但不與一個對象或集合。

您可以做的是在封閉物內手動創建$errors

我測試過它,它按預期工作:

Blade::directive('showIfError', function($fieldName) { 
    $errors = session('errors'); 

    if ($errors->has($fieldName)) { 
     return "<span class='help-block'>".$errors->first($fieldName)."</span>"; 
    } 
}); 
0

的問題是,$錯誤變量只是在視圖中可用。如果您查看共享變量的中間件(https://github.com/laravel/framework/blob/5.0/src/Illuminate/View/Middleware/ShareErrorsFromSession.php),您將看到它存儲在會話中。

所以,你可以通過以下方式訪問它:在你的榜樣

$errors = session()->get('errors'); 

注意你有一對夫婦的其他問題; $ fieldName變量不應該用引號引起來。例如:

public function boot() { 
Blade::directive('showIfError', function($fieldName) { 
$errors = session()->get('errors'); 
if ($errors->has($fieldName)) { 
     echo "<span class='help-block'> <strong>". $errors->first($fieldName). "</strong> </span>"; 
} 
}); 
} 
0

我終於在視圖中寫了一個PHP函數,並用各種字段名稱來調用它。 我希望這是一個好方法。不知道什麼是最好的方式來實現這一點。

function showIfError($fieldName) 
{ 
    $errors=session('errors'); 
    if (count($errors)>0) { 
     if (session('errors')->has($fieldName)) { 
      $msg=$errors->first($fieldName); 
      echo '<span class="help-block"> 
        <strong>'. $msg.' </strong> 
       </span>'; 
     } 
    } 

} 
2

這是遲到的回覆,但希望它會幫助另一個人來。自定義刀片指令應該返回一個字符串php代碼,將在模板呈現時進行評估。由於$errors變量僅在做出響應時可用,因此無法在指令中對其進行評估。解決辦法是這樣的:

// custom blade directive to render the error block if input has error 
// put this inside your service provider's boot method 

    \Blade::directive('errorBlock', function ($input) { 
      return 
       '<?php if($errors->has('.$input.')):?> 
        <div class=\'form-control-feedback\'> 
         <i class=\'icon-cancel-circle2\'></i> 
        </div> 
        <span class=\'help-block\'> 
          <strong><?php echo $errors->first('.$input.') ?></strong> 
        </span> 
       <?php endif;?>'; 
     });