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()

        //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 = Role::find(2);
        $user = $this->guard()->user();
        logg($user->can('view admins'));

//Sync permissions

//Delete all permissions of this role

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->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');

Use middeware

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

Trait for controller to use

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){

    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);


Line #285

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