Laravel 5.1 @can,如何使用OR子句

时间:2015-12-09 20:34:15

标签: laravel laravel-5.1 blade laravel-blade

我没有找到如何在@can视图中使用子句(OR,AND)来检查多个异能......

我试过了:

@can(['permission1', 'permission2']) 
@can('permission1' or 'permission2')
@can('permission1' || 'permission2')

但是不行;(

8 个答案:

答案 0 :(得分:25)

您可以使用Gate facade:

@if(Gate::check('permission1') || Gate::check('permission2'))

@endif

答案 1 :(得分:9)

@canany刀片指令已于2018年5月24日添加到Laravel v.5.6.23

用法:

@canany(['edit posts', 'delete posts'])
    <div class="actions">
        @can('edit posts')
            <button>Edit post</button>
        @endcan
        @can('delete posts')
            <button>Delete post</button>
        @endcan
    </div>
@endcanany

答案 2 :(得分:5)

我在Laravel 5.4应用程序中添加了此指令,允许我在刀片视图中使用新的@canany('write|delete')指令。

// AppServiceProvider.php@boot()

Blade::directive('canany', function ($arguments) {
    list($permissions, $guard) = explode(',', $arguments.',');

    $permissions = explode('|', str_replace('\'', '', $permissions));

    $expression = "<?php if(auth({$guard})->check() && ( false";
    foreach ($permissions as $permission) {
        $expression .= " || auth({$guard})->user()->can('{$permission}')";
    }

    return $expression . ")): ?>";
});

Blade::directive('endcanany', function () {
    return '<?php endif; ?>';
});

刀片视图中的示例:

@canany('write|create')
    ...
@endcanany

这里是doc for extending Blade on 5.4

答案 3 :(得分:2)

您可以多次致电@can

@ if(@can('permission1')|| @can('permission2'))

@if( Gate::check('permission1') || Gate::check('permission2') )

答案 4 :(得分:1)

can上使用Authenticated User方法,

@if ( Auth::user()->can('permission1', App\Model::class) || Auth::user()->can('permission2',  App\Model::class) )

@endif

答案 5 :(得分:1)

如果您使用的是laravel spatie package,则可以通过以下方式轻松实现。

使用hasAnyPermission()方法

@if(auth()->user()->hasAnyPermission(['permission1','permission2']))
   // statements 
@endif

答案 6 :(得分:0)

@if(Gate::check('manage-users') || Gate::check('add-new-user')) 管理用户

    <li>
      <a href="{{url('/back/users')}}">
        <i class="feather icon-users"></i>
       <span class="menu-item" data-i18n="users">Manage Users</span>
        </a>
    </li>

@endif

答案 7 :(得分:-1)

只需使用@canany(['permision1','permision2'])