dongyu2764 2016-11-20 04:55
浏览 160

Laravel扩展刀片模板 - $ errors集合中的错误

I am using Laravel 5.3. My first Laravel project/learning experience In my blade file I use the following snippet to show the errors below a field after a PUT or POST request.

In this case the database field is called firstName

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

Now since I have lot of fields, I have keep repeatings this block for every field. I looked up the Laravel docs on Blade templates (Extending Blade section) and thought I could do the following in the AppServiceProvider class (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>";
        }
    });
}

and then use

@showIfError('firstName')

But no luck...I get the error 'Undefined variable: errors'

Looks like the Laravel error collection is not accessible in this view file.

Appreciate any help. Thanks.

  • 写回答

4条回答 默认 最新

  • dongnong3799 2016-11-20 05:01
    关注

    The thing is $errors in not accessible in closure. Also, you can't pass whole object as directive closure accepts string only. With simple data you can implode() and then explode() it, but not with an object or a collection.

    What you can do is to create $errors manually inside the closure.

    I've tested it and it works as expected:

    Blade::directive('showIfError', function($fieldName) {
        $errors = session('errors');
    
        if ($errors->has($fieldName)) {
            return "<span class='help-block'>".$errors->first($fieldName)."</span>";
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号