Lucas Lopes Lucas Lopes - 2 months ago 38
PHP Question

Menu filter permission with Laratrust

I'm using AdminLTE and Lara Entrust created a MyMenu Filter.php file to filter my options in accordance with the permission menu.

adminlte.php

'menu' => [
'MAIN NAVIGATION',
[
'text' => 'Blog',
'url' => 'admin/blog',
'permission' => 'create-post',
],
// CODE...
],

'filters' => [
// CODE...
App\MyMenuFilter::class,
],


MyMenuFilter.php

<?php

namespace App;

use JeroenNoten\LaravelAdminLte\Menu\Builder;
use JeroenNoten\LaravelAdminLte\Menu\Filters\FilterInterface;

class MyMenuFilter implements FilterInterface
{
public function transform($item, Builder $builder)
{
if (isset($item['permission']) && \Laratrust::can($item['permission'])) {
return false;
}

return $item;
}
}


My option in the "blog" menu need the create-post permission. But the "if" in mymenufilter.php returns false quando o usuário tem a permissão and does not create the menu.

But if I put a permission that the user does not have, it appears.

Answer

I think you've just got the logic backwards. You should return false if the user CANNOT use the permission. I have added a ! (not) in the if statement below. This should fix your problem

public function transform($item, Builder $builder)
{
    if (isset($item['permission']) && !\Laratrust::can($item['permission'])) {
        return false;
    }

    return $item;
}