arrilot / laravel-widgets

Widgets for Laravel

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Render widgets by condition

cyrildewit opened this issue · comments

I am currently working on a feature for Voyager.

They have a dimmers.blade.php file where they retrieve all the widgets with:

$dimmers = \Arrilot\Widgets\Facade::group('voyager::dimmers');

These dimmers are stored in the VoyagerDummyServiceProvider.php (registerWidgets method).

$default_widgets = [
    'TCG\\Voyager\\Widgets\\UserDimmer',
    'TCG\\Voyager\\Widgets\\PostDimmer',
    'TCG\\Voyager\\Widgets\\PageDimmer'
];
$widgets = config('voyager.dashboard.widgets', $default_widgets);

foreach ($widgets as $widget) {
    Widget::group('voyager::dimmers')->addWidget($widget);
}

And they display the dimmers with:

@php
$count = $dimmers->count();

$classes = [
    'col-xs-12',
    'col-sm-'.($count >= 2 ? '6' : '12'),
    'col-md-'.($count >= 3 ? '4' : ($count >= 2 ? '6' : '12')),
];
$class = implode(' ', $classes);
$prefix = "<div class='{$class}'>";
$surfix = '</div>';
@endphp
@if ($dimmers->any())
<div class="clearfix container-fluid row">
    {!! $prefix.$dimmers->setSeparator($surfix.$prefix)->display().$surfix !!}
</div>
@endif

What I want to do is checking if the current user has the permissions to be able to browse the widget's content. I tried all kind of stuff. Adding a @can('read_xxx') in the widget's view, but because it's injected into a grid that's based upon the number of widgets it will just keep a collumn empty. Something like: dimmer 1 -- empty space -- dimmer 3. I also tried to check the permission when booting, but this is not possible because the user object is null.

It would be nice If I could do something like:

$user = Auth::user();

$dimmers->displayIf(function($widget) use ($user) {
    return $user->can('browse', $widget->relatedModel()); // returns bool
})

->relatedModel() is a simple function that returns the related model.

Or do you have a better solution in mind?

Thank you in advance!

Well, in my opinion one should not add a widget to a group if the current user has no permission to view it.
Isn't it possible to add a check there?