我正在使用spatie权限包:https://github.com/spatie/laravel-permission
该软件包没有指令来检查用户是否拥有任何权限,但方法hasAnyPermission
确实存在。
我正在尝试在刀片中使用以下条件:
@if (auth()->user()->hasAnyPermission(['View Users', 'View Roles']))
这导致Trying to get property of non-object
错误。
为什么会这样?
修改
我将在布局中发布更多代码:
@if (auth()->guest())
<!-- Guest Menu -->
<li {{ (request()->is('login') ? 'class=active' : '') }}><a href="{{ route('login') }}">Login</a></li>
@if (config('lion.allow_registration'))
<li {{ (request()->is('register') ? 'class=active' : '') }}><a href="{{ route('register') }}">Register</a></li>
@endif
@else
<!-- Auth Menu -->
@if (auth()->user()->hasAnyPermission(['View Users', 'View Roles']))
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Settings <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
@can('View Users')
<li {{ (request()->is('users') ? 'class=active' : '') }}><a href="{{ route('users') }}">Users</a></li>
@endcan
@can('View Roles')
<li {{ (request()->is('roles') ? 'class=active' : '') }}><a href="{{ route('roles') }}">Roles</a></li>
@endcan
</ul>
</li>
@endif
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ auth()->user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li {{ (request()->is('profile') ? 'class=active' : '') }}><a href="{{ route('profile') }}">Profile</a></li>
<li><a href="{{ route('logout') }}">Logout</a></li>
</ul>
</li>
@endif
此代码在没有条件语句@if (auth()->user()->hasAnyPermission(['View Users', 'View Roles']))
的情况下完美运行。
答案 0 :(得分:0)
我最终只是为此创建了一个自定义刀片指令:
Blade::directive('hasanypermission', function ($permissions) {
$permissions = explode(',', $permissions);
$conditional = [];
foreach ($permissions as $permission) {
$conditional[] = "Gate::check($permission)";
}
return "<?php if (".implode(' || ', $conditional)."): ?>";
});
Blade::directive('endhasanypermission', function () {
return '<?php endif; ?>';
});
如何使用它:
@hasanypermission('Read Users', 'Read Roles')
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
Settings <span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
@can('Read Users')
<li {{ (request()->is('users') ? 'class=active' : '') }}><a href="{{ route('users') }}">Users</a></li>
@endcan
@can('Read Roles')
<li {{ (request()->is('roles') ? 'class=active' : '') }}><a href="{{ route('roles') }}">Roles</a></li>
@endcan
</ul>
</li>
@endhasanypermission