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/ */

    

mdnayeemsarker / role-permission example snippets

bash
php artisan vendor:publish --provider="Mdnayeemsarker\RolePermission\MnsRpServiceProvider"
bash
php artisan config:clear
php artisan cache:clear
composer dump-autoload
bash
php artisan migrate
bash
php artisan db:seed
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
"autoload": {
    "files": [
        "app/Http/Helper.php"
    ]
}
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;
    }
}