Displaying and hiding links based on access permissions

18 Views Asked by At

I have a 'users' table that maintains a one-to-one relationship with the 'page_access_management' table. This table includes fields such as 'emp_create', 'view', 'delete', 'edit', etc., and I set their values to one or zero. I am using Passport authentication and storing the user's details in the session, but I am not storing the 'page_access_management' details in the session. I have a link to create an employee:

<a class="nav-link {{ Route::currentRouteName() === 'employee.create' ? 'active' : '' }}" href="{{ route('employee.create') }}">Add Employee</a> 

I want this link hidden if the user is not authorized to create an employee.

protected function checkPermission($permissionName)
{
    $user_session = session('user');
    $userId = $user_session->id;

    $hasPermission = User::whereHas('pageAccessManagements', function ($query) use ($userId, $permissionName) {
        $query->where('user_id', $userId)->where($permissionName, 1);
    })->exists();

    return $hasPermission;
}

I want to use this function to prevent the routes from unauthorized users.

1

There are 1 best solutions below

0
Karl Hill On

Use the checkPermission function in your blade file to display the link conditionally based on the user's permission.

@if(checkPermission('emp_create'))
    <a class="nav-link {{ Route::currentRouteName() === 'employee.create' ? 'active' : '' }}" href="{{ route('employee.create') }}">Add Employee</a> 
@endif