Your allowed() helper might prove to be fatal as it makes lots of database calls and iterates through a lot of data with EACH call to it. And you will be making several calls to this helper.
Insted, try this :
Create a accessor in your user model to retrive and cache all the routes the current user is allowed to access.
Modify your helper :
if (!function_exists("allowed"))
{
function allowed($route)
{
if ( ! Auth::check()) return false;
return in_array($route, Auth::user()->routes);
}
}
if( ! function_exists('acl_link_to_route'))
{
function acl_link_to_route($route, $title, $parameters = [], $attributes = []);
{
if(allowed($route))
echo link_to_route($route, $title, $parameters, $attributes);
}
}
<td>
{{ acl_link_to_route('group.edit', 'Edit', ['id' => $group->id]) }}
{{ acl_link_to_route('group.edit', 'Delete', ['id' => $group->id], ['class' => 'confirm', 'data-confirm' => 'Are... ?']) }}
</td>
It will return html a tag link to your route if its allowed, else, nothing.
Would creating the accessor be like this
public function getRoutesAttribute($route){
return ucfirst($route);
}
It's in my user model
More like :
public function getRoutesAttribute()
{
$routes = $this->groups->each(function ($group)
{
return $group->resources->each(function($resource)
{
return $resource->name;
});
});
return array_dot($routes);
}
Now you can use the Auth::user()->routes
in the in_array()
check.
Hi,
Thanks for your help, but the code you gave me isn't working 100%. It doesn't show up when the user is able to access the page.
For example
The user Jane is allowed to access edit groups, which uses
{{ acl_link_to_route('group.edit', 'Edit 1', ['id' => $group->id]) }}
But the user John isn't allowed to access the edit groups page.
I managed to fix it.
I removed
if(!function_exists("allowed")){
function allowed($route){
if(!Auth::check()) return false;
return in_array($route, Auth::user()->routes);
}
}
and put back
if (!function_exists("allowed"))
{
function allowed($route)
{
if (Auth::check())
{
foreach (Auth::user()->groups as $group)
{
foreach ($group->resources as $resource)
{
if ($resource->name == $route)
{
return true;
}
}
}
}
return false;
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community