#NOTE about using permission names in policies The second will be a collection with the edit article permission and the third will contain both. If we follow the previous example, the first response will be a collection with the delete article permission and You can examine all of these permissions: // Direct permissions $user -> getDirectPermissions () // Or $user->permissions // Permissions inherited from the user's roles $user -> getPermissionsViaRoles () // All permissions which apply on the user (inherited and direct) $user -> getAllPermissions () Īll these responses are collections of Spatie\Permission\Models\Permission objects. $user->hasAnyDirectPermission('edit articles'), it returns true because the user has one of the provided permissions. It returns false, because the user does not have edit articles as a direct permission. You can check if the user has a Specific or All or Any of a set of permissions directly assigned: // Check if the user has Direct permission $user -> hasDirectPermission ( 'edit articles' ) // Check if the user has All direct permissions $user -> hasAllDirectPermissions () // Check if the user has Any permission directly $user -> hasAnyDirectPermission () īy following the previous example, when we call $user->hasAllDirectPermissions() allowing to change only direct permissions of the user. This method is useful if one builds a form for setting permissions for roles and users in an application and wants to restrict or change inherited permissions of roles of the user, i.e. When we call $user->hasDirectPermission('delete articles') it returns true,īut false for $user->hasDirectPermission('edit articles'). The permission of 'delete articles' is the user's direct permission because it is assigned directly to them. Now the user can edit articles and additionally delete articles. In the above example, a role is given permission to edit articles and this role is assigned to a user. get collection $role -> permissions // return only the permission names: $role -> permissions -> pluck ( 'name' ) // count the number of permissions assigned to a role count ($role -> permissions) // or $role -> permissions -> count () #Assigning Direct Permissions To A UserĪdditionally, individual permissions can be assigned to the user too.įor instance: $role = Role :: findByName ( 'writer' ) $role -> givePermissionTo ( 'edit articles' ) $user -> assignRole ( 'writer' ) $user -> givePermissionTo ( 'delete articles' ) This collection can respond to usual Eloquent Collection operations, such as count, sort, etc. The permissions property on any given role returns a collection with all the related permission objects. NOTE: Permissions are inherited from roles automatically. ![]() String or a Spatie\Permission\Models\Permission object. The givePermissionTo and revokePermissionTo functions can accept a Or revoke
0 Comments
Leave a Reply. |