【问题标题】:Passing an array to Laravel Blade Directive将数组传递给 Laravel Blade 指令
【发布时间】:2020-10-16 15:11:31
【问题描述】:

我试图避免在刀片中执行以下操作

<?php if(auth()->check() && auth()->user()->hasRoles(['administrator', 'superadmin'])) { ?>
...
<?php } ?>

我试过这样的刀片指令;

Blade::directive('roles', function ($roles) {
        return "<?php if (auth()->check() && auth()->user()->hasRoles({$roles}): ?>";
    });

我收到此错误:

syntax error, unexpected ':' (View: /Users/.../index.blade.php)

当我在 laravel Blade 中尝试这个时;

@roles(['admin', 'super-admin'])
...
@endroles

我想在刀片中传递一组角色并执行正确的权限。我在 User 模型上有一个名为 hasRoles(array $roles) 的方法,它接受一个角色数组。

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

    在 if 条件的末尾有一个 ':'

    if (auth()->check() && auth()->user()->hasRoles({$roles}):
    

    改成

    if ( auth()->check() && auth()->user()->hasRoles({$roles}) ) { ... }
    

    【讨论】:

    • 谢谢@Digvijay,我想我已经尝试过了。成功了!
    猜你喜欢
    • 2020-06-03
    • 2022-06-30
    • 2016-05-05
    • 2014-07-17
    • 2016-02-05
    • 2021-06-29
    • 2016-04-12
    • 1970-01-01
    • 2018-08-08
    相关资源
    最近更新 更多