laravel-permission

Official

https://github.com/spatie/laravel-permission

Doc

https://docs.spatie.be/laravel-permission/v3/basic-usage/role-permissions/

Model User

use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;
}

Config “Super Admin” in AuthServiceProvider.php

public function boot()
    {
        $this->registerPolicies();

        //Implicitly grant "Super Admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability) {
            return $user->hasRole('Super Admin') ? true : null;
        });
    }

Controller and related functions

        //$role = Role::create(['name' => 'Super Admin']);
        //$permission = Permission::create(['name' => 'view admins']);
        //$role->givePermissionTo($permission);
        $role = Role::find(2);
        $user = $this->guard()->user();
        $user->assignRole($role);
        logg($user->can('view admins'));
        logg($user);

//Sync permissions
$role->syncPermissions($permissions);

//Delete all permissions of this role
$role->syncPermissions();

Add useful function in model User

$users = User::role('writer')->get();

$users = User::permission('edit articles')->get();

Useful functions:

// get a list of all permissions directly assigned to the user
$permissionNames = $user->getPermissionNames(); // collection of name strings
$permissions = $user->permissions; // collection of permission objects

// get all permissions for the user, either directly, or from roles, or from both
$permissions = $user->getDirectPermissions();
$permissions = $user->getPermissionsViaRoles();
$permissions = $user->getAllPermissions();

// get the names of the user's roles
$roles = $user->getRoleNames(); // Returns a collection

Check permission

$user->hasPermissionTo('edit articles');

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

$user->hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);

$user->hasAnyPermission(['edit articles', 1, 5]);

$user->can('edit articles');

https://docs.spatie.be/laravel-permission/v3/basic-usage/direct-permissions/

Use middeware

Route::group(['middleware' => ['can:publish articles']], function () {
    //
});

Trait for controller to use

<?php
namespace App\Traits;

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
 
// To set $locale value of a model and translate all translatable attributes
trait PermissionCheck
{
    protected function check_pms($pms){
        $user = $this->guard()->user();
        if($user->can($pms) == false){
            show_alert('沒有權限');
        }
    }

    protected function check_pms_ajax($pms){
        $user = $this->guard()->user();
        if($user->can($pms) == false){
            $response = [
                'status' => 'fail', 
                'code' => '2', 
                'message' => '沒有權限'
            ];

            header('Content-Type: application/json');
            echo json_encode($response);
            exit();
        }
    }
}

Bugs

/vendor/spatie/laravel-permission/src/Traits/HasPermissions.php
Line #285

        // Added by Rex 20200527
        // $this->permissions could be an empty string and cause error
        if($this->permissions == false){
            return false;
        }