我使用的是Laravel 5.3。我的第一个Laravel项目/学习经历 在我的刀片文件中,我使用以下代码段在PUT或POST请求后显示字段下方的错误。
在这种情况下,数据库字段称为firstName
@if ($errors->has('firstName'))
<span class="help-block">
<strong>{{ $errors->first('firstName') }}</strong>
</span>
@endif
既然我有很多字段,我会不断为每个字段重复这个块。我在Blade模板(扩展刀片部分)上查找了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(&#39;的firstName&#39)
但没有运气......我收到错误&#39;未定义变量:错误&#39;
看起来在此视图文件中无法访问Laravel错误集合。
感谢任何帮助。感谢。
答案 0 :(得分: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;?>';
});
答案 1 :(得分:1)
关闭时无法访问DefinePlugin
。此外,您不能传递整个对象,因为指令闭包只接受字符串。使用简单数据,您可以$errors
然后implode()
,但不能使用对象或集合。
您可以做的是在闭包内手动创建explode()
。
我已经测试了它,它按预期工作:
$errors
答案 2 :(得分:0)
问题是$ errors变量仅在视图中可用。如果您查看共享变量(https://github.com/laravel/framework/blob/5.0/src/Illuminate/View/Middleware/ShareErrorsFromSession.php)的中间件,您将看到它存储在会话中。
所以你可以按如下方式访问它:
#include
请注意,在您的示例中,您还有其他一些问题; $ fieldName变量不应该在引号中。例如:
$errors = session()->get('errors');
答案 3 :(得分: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>';
}
}
}