PHP code example of mdnayeemsarker / role-permission
1. Go to this page and download the library: Download mdnayeemsarker/role-permission library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
bash
// Define the relationship with Role (Override)
public function role()
{
return $this->belongsToMany(Role::class, 'user_roles');
}
// Define the relationship with Permissions
public function allPermissions()
{
return $this->role->flatMap->permissions;
}
bash
namespace App\Helpers;
use Illuminate\Support\Facades\Auth;
class PermissionHelper
{
/**
* Check if the authenticated user has a specific permission.
*
* @param string $permission
* @return bool
*/
public static function hasPermission($ppermissionName)
{
$user = Auth::user();
if ($user && $user->role()->exists()) {
$permissions = $user->allPermissions();
return $permissions->contains('name', $permissionName);
}
return false;
}
}
bash
if (!function_exists('hasPermission')) {
/**
* Check if the authenticated user has a specific permission.
*
* @param string $permission
* @return bool
*/
function hasPermission($permissionName)
{
$user = Auth::user();
if ($user && $user->role()->exists()) {
$permissions = $user->allPermissions();
return $permissions->contains('name', $permissionName);
}
return false;
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.