Skip to content

Commit

Permalink
Merge branch 'main' into patch-3
Browse files Browse the repository at this point in the history
  • Loading branch information
drbyte authored Jul 14, 2023
2 parents 7074193 + ed0de82 commit e1e9069
Show file tree
Hide file tree
Showing 37 changed files with 909 additions and 224 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dependabot-auto-merge.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:

- name: Dependabot metadata
id: metadata
uses: dependabot/fetch-metadata@v1.4.0
uses: dependabot/fetch-metadata@v1.6.0
with:
github-token: "${{ secrets.GITHUB_TOKEN }}"
compat-lookup: true
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/fix-php-code-style-issues.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
ref: ${{ github.head_ref }}

- name: Fix PHP code style issues
uses: aglipanci/laravel-pint-action@2.2.0
uses: aglipanci/laravel-pint-action@2.3.0

- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
Expand Down
67 changes: 67 additions & 0 deletions .github/workflows/test-cache-drivers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
name: "Run Tests - Cache Drivers"

on: [push, pull_request]

jobs:
cache:

runs-on: ubuntu-latest

services:
redis:
image: redis
ports:
- 6379/tcp
options: --health-cmd="redis-cli ping" --health-interval=10s --health-timeout=5s --health-retries=3

strategy:
fail-fast: false

name: Cache Drivers

steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.2
extensions: curl, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, iconv, memcache
coverage: none

- name: Install dependencies
run: |
composer require "predis/predis" --no-interaction --no-update
composer update --prefer-stable --prefer-dist --no-interaction
- name: Execute tests - memcached cache driver
run: |
vendor/bin/phpunit
env:
CACHE_DRIVER: memcached

- name: Execute tests - redis cache driver
run: |
vendor/bin/phpunit
env:
CACHE_DRIVER: redis
REDIS_PORT: ${{ job.services.redis.ports['6379'] }}

- name: Execute tests - database cache driver
run: |
vendor/bin/phpunit
env:
CACHE_DRIVER: database

- name: Execute tests - file cache driver
run: |
vendor/bin/phpunit
env:
CACHE_DRIVER: file

- name: Execute tests - array cache driver
run: |
vendor/bin/phpunit
env:
CACHE_DRIVER: array
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

All notable changes to `laravel-permission` will be documented in this file

## 5.10.2 - 2023-07-04

### What's Changed

- Fix Eloquent Strictness on `permission:show` Command by @erikn69 in https://github.com/spatie/laravel-permission/pull/2457

**Full Changelog**: https://github.com/spatie/laravel-permission/compare/5.10.1...5.10.2

## 5.10.1 - 2023-04-12

### What's Changed
Expand Down Expand Up @@ -609,6 +617,7 @@ The following changes are not "breaking", but worth making the updates to your a




```
1. Also this is a good time to point out that now with v2.25.0 and v2.26.0 most permission-cache-reset scenarios may no longer be needed in your app, so it's worth reviewing those cases, as you may gain some app speed improvement by removing unnecessary cache resets.

Expand Down Expand Up @@ -664,6 +673,7 @@ The following changes are not "breaking", but worth making the updates to your a




```
## 2.19.1 - 2018-09-14

Expand Down
27 changes: 15 additions & 12 deletions config/permission.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@

/*
* When set to true, the method for checking permissions will be registered on the gate.
* Set this to false, if you want to implement custom logic for checking permissions.
* Set this to false if you want to implement custom logic for checking permissions.
*/

'register_permission_check_method' => true,
Expand All @@ -111,33 +111,36 @@
'register_octane_reset_listener' => false,

/*
* When set to true the package implements teams using the 'team_foreign_key'. If you want
* the migrations to register the 'team_foreign_key', you must set this to true
* before doing the migration. If you already did the migration then you must make a new
* migration to also add 'team_foreign_key' to 'roles', 'model_has_roles', and
* 'model_has_permissions'(view the latest version of package's migration file)
* Teams Feature.
* When set to true the package implements teams using the 'team_foreign_key'.
* If you want the migrations to register the 'team_foreign_key', you must
* set this to true before doing the migration.
* If you already did the migration then you must make a new migration to also
* add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions'
* (view the latest version of this package's migration file)
*/

'teams' => false,

/*
* When set to true, the required permission names are added to the exception
* message. This could be considered an information leak in some contexts, so
* the default setting is false here for optimum safety.
* When set to true, the required permission names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/

'display_permission_in_exception' => false,

/*
* When set to true, the required role names are added to the exception
* message. This could be considered an information leak in some contexts, so
* the default setting is false here for optimum safety.
* When set to true, the required role names are added to exception messages.
* This could be considered an information leak in some contexts, so the default
* setting is false here for optimum safety.
*/

'display_role_in_exception' => false,

/*
* By default wildcard permission lookups are disabled.
* See documentation to understand supported syntax.
*/

'enable_wildcard_permission' => false,
Expand Down
47 changes: 37 additions & 10 deletions docs/advanced-usage/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,43 @@ title: Extending
weight: 4
---

## Adding fields to your models
You can add your own migrations to make changes to the role/permission tables, as you would for adding/changing fields in any other tables in your Laravel project.

Following that, you can add any necessary logic for interacting with those fields into your custom/extended Models.

Here is an example of adding a 'description' field to your Permissions and Roles tables:

```sh
php artisan make:migration add_description_to_permissions_tables
```
And in the migration file:
```php
public function up()
{
Schema::table('permissions', function (Blueprint $table) {
$table->string('description')->nullable();
});
Schema::table('roles', function (Blueprint $table) {
$table->string('description')->nullable();
});
}
```

Semi-Related article: [Adding Extra Fields To Pivot Table](https://quickadminpanel.com/blog/laravel-belongstomany-add-extra-fields-to-pivot-table/) (video)

## Adding a description to roles and permissions
A common question is "how do I add a description for my roles or permissions?".

By default, a 'description' field is not included in this package, to keep the model memory usage low, because not every app has a need for displayed descriptions.

But you are free to add it yourself if you wish. You can use the example above.

### Multiple Language Descriptions

If you need your 'description' to support multiple languages, simply use Laravel's built-in language features. You might prefer to rename the 'description' field in these migration examples from 'description' to 'description_key' for clarity.


## Extending User Models
Laravel's authorization features are available in models which implement the `Illuminate\Foundation\Auth\Access\Authorizable` trait.

Expand Down Expand Up @@ -58,13 +95,3 @@ In the rare case that you have need to REPLACE the existing `Role` or `Permissio
- Your `Permission` model needs to implement the `Spatie\Permission\Contracts\Permission` contract
- You need to update `config/permission.php` to specify your namespaced model


## Adding fields to your models
You can add your own migrations to make changes to the role/permission tables, as you would for adding/changing fields in any other tables in your Laravel project.

Following that, you can add any necessary logic for interacting with those fields into your custom/extended Models.

Related article: [Adding Extra Fields To Pivot Table](https://quickadminpanel.com/blog/laravel-belongstomany-add-extra-fields-to-pivot-table/) (video)



28 changes: 22 additions & 6 deletions docs/basic-usage/basic-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ title: Basic Usage
weight: 1
---

## Add The Trait
First, add the `Spatie\Permission\Traits\HasRoles` trait to your `User` model(s):

```php
Expand All @@ -17,6 +18,7 @@ class User extends Authenticatable
}
```

## Create A Permission
This package allows for users to be associated with permissions and roles. Every role is associated with multiple permissions.
A `Role` and a `Permission` are regular Eloquent models. They require a `name` and can be created like this:

Expand All @@ -28,30 +30,34 @@ $role = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit articles']);
```


## Assign A Permission To A Role
A permission can be assigned to a role using either of these methods:

```php
$role->givePermissionTo($permission);
$permission->assignRole($role);
```

## Sync Permissions To A Role
Multiple permissions can be synced to a role using either of these methods:

```php
$role->syncPermissions($permissions);
$permission->syncRoles($roles);
```

## Remove Permission From A Role
A permission can be removed from a role using either of these methods:

```php
$role->revokePermissionTo($permission);
$permission->removeRole($role);
```

## Guard Name
If you're using multiple guards then the `guard_name` attribute must be set as well. Read about it in the [using multiple guards](./multiple-guards) section of the readme.

## Get Permissions For A User
The `HasRoles` trait adds Eloquent relationships to your models, which can be accessed directly or used as a base query:

```php
Expand All @@ -68,31 +74,41 @@ $permissions = $user->getAllPermissions();
$roles = $user->getRoleNames(); // Returns a collection
```

The `HasRoles` trait also adds a `role` scope to your models to scope the query to certain roles or permissions:
## Scopes
The `HasRoles` trait also adds `role` and `withoutRole` scopes to your models to scope the query to certain roles or permissions:

```php
$users = User::role('writer')->get(); // Returns only users with the role 'writer'
$nonEditors = User::withoutRole('editor')->get(); // Returns only users without the role 'editor'
```

The `role` scope can accept a string, a `\Spatie\Permission\Models\Role` object or an `\Illuminate\Support\Collection` object.
The `role` and `withoutRole` scopes can accept a string, a `\Spatie\Permission\Models\Role` object or an `\Illuminate\Support\Collection` object.

The same trait also adds a scope to only get users that have a certain permission.
The same trait also adds scopes to only get users that have or don't have a certain permission.

```php
$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles' (inherited or directly)
$usersWhoCannotEditArticles = User::withoutPermission('edit articles')->get(); // Returns all users without the permission 'edit articles' (inherited or directly)
```

The scope can accept a string, a `\Spatie\Permission\Models\Permission` object or an `\Illuminate\Support\Collection` object.


### Eloquent
## Eloquent Calls
Since Role and Permission models are extended from Eloquent models, basic Eloquent calls can be used as well:

```php
$all_users_with_all_their_roles = User::with('roles')->get();
$all_users_with_all_direct_permissions = User::with('permissions')->get();
$all_users_with_all_their_direct_permissions = User::with('permissions')->get();
$all_roles_in_database = Role::all()->pluck('name');
$users_without_any_roles = User::doesntHave('roles')->get();
$all_roles_except_a_and_b = Role::whereNotIn('name', ['role A', 'role B'])->get();
```

## Counting Users Having A Role
One way to count all users who have a certain role is by filtering the collection of all Users with their Roles:
```php
$superAdminCount = User::with('roles')->get()->filter(
fn ($user) => $user->roles->where('name', 'Super Admin')->toArray()
)->count();
```
2 changes: 2 additions & 0 deletions docs/basic-usage/enums.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ weight: 4

## Enum Prerequisites

Requires `version 6` of this package.

Requires PHP 8.1 or higher.

If you are using PHP 8.1+ you can implement Enums as native types.
Expand Down
30 changes: 29 additions & 1 deletion docs/basic-usage/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,18 @@ Route::group(['middleware' => ['can:publish articles']], function () {
});
```

In Laravel v10.9 and up, you can also call this middleware with a static method.

```php
Route::group(['middleware' => [\Illuminate\Auth\Middleware\Authorize::using('publish articles')]], function () {
//
});
```

## Package Middleware

This package comes with `RoleMiddleware`, `PermissionMiddleware` and `RoleOrPermissionMiddleware` middleware. You can add them inside your `app/Http/Kernel.php` file.
This package comes with `RoleMiddleware`, `PermissionMiddleware` and `RoleOrPermissionMiddleware` middleware.
You can add them inside your `app/Http/Kernel.php` file to be able to use them through aliases.

Note the property name difference between Laravel 10 and older versions of Laravel:

Expand Down Expand Up @@ -88,3 +97,22 @@ public function __construct()
```

(You can use Laravel's Model Policy feature with your controller methods. See the Model Policies section of these docs.)

## Use middleware static methods

All of the middlewares can also be applied by calling the static `using` method,
which accepts either a `|`-separated string or an array as input.

```php
Route::group(['middleware' => [\Spatie\Permission\Middlewares\RoleMiddleware::using('super-admin')]], function () {
//
});

Route::group(['middleware' => [\Spatie\Permission\Middlewares\PermissionMiddleware::using('publish articles|edit articles')]], function () {
//
});

Route::group(['middleware' => [\Spatie\Permission\Middlewares\RoleOrPermissionMiddleware::using(['super-admin', 'edit articles'])]], function () {
//
});
```
2 changes: 1 addition & 1 deletion docs/basic-usage/teams-permissions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ When enabled, teams permissions offers you flexible control for a variety of sce

NOTE: These configuration changes must be made **before** performing the migration when first installing the package.

If you have already run the migration and want to upgrade your implementation, you can run the artisan console command `php artisan spatie-permission:setup-teams`, to create a new migration file named [xxxx_xx_xx_xx_add_teams_fields.php](https://github.com/spatie/laravel-permission/blob/main/database/migrations/add_teams_fields.php.stub) and then run `php artisan migrate` to upgrade your database tables.
If you have already run the migration and want to upgrade your implementation, you can run the artisan console command `php artisan permission:setup-teams`, to create a new migration file named [xxxx_xx_xx_xx_add_teams_fields.php](https://github.com/spatie/laravel-permission/blob/main/database/migrations/add_teams_fields.php.stub) and then run `php artisan migrate` to upgrade your database tables.

Teams permissions can be enabled in the permission config file:

Expand Down
Loading

0 comments on commit e1e9069

Please sign in to comment.