Laravel 5 自定义@can()以显示页面/节的权限覆盖
在工作中,我维护了一个相当复杂的Laravel应用程序,随着新功能的实现和改进,该应用程序仍在增长 我们在这个系统中有非技术管理员,他们管理其他用户的权限,有时很难知道什么权限会阻止用户访问某个页面,或者什么权限会给用户太多的访问权限。更好地描述权限和模拟用户查看他们有权访问的内容的能力是我们已经做过的事情 除此之外,我们希望为刀片模板中定义的权限切换覆盖,我们可以使用Laravel 5 自定义@can()以显示页面/节的权限覆盖,laravel-5,laravel-5.4,laravel-blade,Laravel 5,Laravel 5.4,Laravel Blade,在工作中,我维护了一个相当复杂的Laravel应用程序,随着新功能的实现和改进,该应用程序仍在增长 我们在这个系统中有非技术管理员,他们管理其他用户的权限,有时很难知道什么权限会阻止用户访问某个页面,或者什么权限会给用户太多的访问权限。更好地描述权限和模拟用户查看他们有权访问的内容的能力是我们已经做过的事情 除此之外,我们希望为刀片模板中定义的权限切换覆盖,我们可以使用 @can('update', $post) <!-- Menu button to update a $post
@can('update', $post)
<!-- Menu button to update a $post -->
@endcan
@can('update',$post)
@恩德坎
或
@can('manage\u user\u roles\u和\u permissions')
@恩德坎
是否有一种方法可以修改@can()
在刀片式模板中的工作方式,以便我可以添加一些javascript来显示一个分区开始和结束的弹出窗口,例如“需要权限“show Post”才能显示此菜单按钮”或“要查看以下分区,用户需要“管理用户角色和权限”权限”. 或者,如果我可以在分区周围添加一个带红色边框的div,那就更好了
如何在刀片模板中使用@can()来显示覆盖的地方附加额外的javascript/html。要解决此问题,我需要扩展刀片,请参阅Laravel文档中的 下面是一个快速测试,我只是想看看这是否可行<代码>$value在本例中是一个字符串,其中包含刀片文件在处理前的内容。因此,我可以使用
preg\u match\u all()
查找@can
语句,然后在需要的地方附加我的javascript。我可以用同样的方法找到@endcan
,但很难知道哪个@endcan
属于哪个@can
,但从这一点开始,应该很容易匹配
<?php
namespace App\Providers;
use Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::extend(function($value)
{
$can_array = array();
preg_match_all('/(\s*)@(can)\(([^\)]*)\)(\s*)/', $value, $matches);
if (count($matches) > 0 && isset($matches[3])) {
foreach ($matches[3] as $match) {
if (!in_array($match, $can_array)) {
$can_array[] = $match;
}
}
}
foreach ($can_array as $ca) {
$value = str_replace("@can(" . $ca . ")", "@can(" . $ca . ") \r\n <!-- My javascript code goes here! -->", $value);
}
// TODO need to figure out a better way to handle this
$value = str_replace("@endcan", "@endcan \r\n <!-- Section ended here -->", $value);
return $value;
});
}
...
<?php
namespace App\Providers;
use Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Blade::extend(function($value)
{
$can_array = array();
preg_match_all('/(\s*)@(can)\(([^\)]*)\)(\s*)/', $value, $matches);
if (count($matches) > 0 && isset($matches[3])) {
foreach ($matches[3] as $match) {
if (!in_array($match, $can_array)) {
$can_array[] = $match;
}
}
}
foreach ($can_array as $ca) {
$value = str_replace("@can(" . $ca . ")", "@can(" . $ca . ") \r\n <!-- My javascript code goes here! -->", $value);
}
// TODO need to figure out a better way to handle this
$value = str_replace("@endcan", "@endcan \r\n <!-- Section ended here -->", $value);
return $value;
});
}
...