update inbox list

This commit is contained in:
manhlab
2021-04-07 19:25:18 -04:00
parent fda7245f7c
commit 436de2efd6
8576 changed files with 1013325 additions and 3 deletions

View File

@@ -0,0 +1,4 @@
---
title: Advanced usage
weight: 3
---

View File

@@ -0,0 +1,47 @@
---
title: Cache
weight: 5
---
Role and Permission data are cached to speed up performance.
While we recommend not changing the cache "key" name, if you wish to alter the expiration time you may do so in the `config/permission.php` file, in the `cache` array.
When you use the built-in functions for manipulating roles and permissions, the cache is automatically reset for you, and relations are automatically reloaded for the current model record:
```php
$user->assignRole('writer');
$user->removeRole('writer');
$user->syncRoles(params);
$role->givePermissionTo('edit articles');
$role->revokePermissionTo('edit articles');
$role->syncPermissions(params);
$permission->assignRole('writer');
$permission->removeRole('writer');
$permission->syncRoles(params);
```
HOWEVER, if you manipulate permission/role data directly in the database instead of calling the supplied methods, then you will not see the changes reflected in the application unless you manually reset the cache.
Additionally, because the Role and Permission models are Eloquent models which implement the `RefreshesPermissionCache` trait, creating and deleting Roles and Permissions will automatically clear the cache. If you have created your own models which do not extend the default models then you will need to implement the trait yourself.
### Manual cache reset
To manually reset the cache for this package, you can run the following in your app code:
```php
app()->make(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
```
Or you can use an Artisan command:
```bash
php artisan permission:cache-reset
```
### Cache Identifier
TIP: If you are leveraging a caching service such as `redis` or `memcached` and there are other sites
running on your server, you could run into cache clashes between apps. It is prudent to set your own
cache `prefix` in Laravel's `/config/cache.php` to something unique for each application.
This will prevent other applications from accidentally using/changing your cached data.

View File

@@ -0,0 +1,26 @@
---
title: Exceptions
weight: 3
---
If you need to override exceptions thrown by this package, you can simply use normal [Laravel practices for handling exceptions](https://laravel.com/docs/errors#render-method).
An example is shown below for your convenience, but nothing here is specific to this package other than the name of the exception.
You can find all the exceptions added by this package in the code here: https://github.com/spatie/laravel-permission/tree/master/src/Exceptions
**app/Exceptions/Handler.php**
```php
public function render($request, Throwable $exception)
{
if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException) {
return response()->json([
'responseMessage' => 'You do not have the required authorization.',
'responseStatus' => 403,
]);
}
return parent::render($request, $exception);
}
```

View File

@@ -0,0 +1,35 @@
---
title: Extending
weight: 4
---
## Extending User Models
Laravel's authorization features are available in models which implement the `Illuminate\Foundation\Auth\Access\Authorizable` trait.
By default Laravel does this in `\App\User` by extending `Illuminate\Foundation\Auth\User`, in which the trait and `Illuminate\Contracts\Auth\Access\Authorizable` contract are declared.
If you are creating your own User models and wish Authorization features to be available, you need to implement `Illuminate\Contracts\Auth\Access\Authorizable` in one of those ways as well.
## Extending Role and Permission Models
If you are extending or replacing the role/permission models, you will need to specify your new models in this package's `config/permission.php` file.
First be sure that you've published the configuration file (see the Installation instructions), and edit it to update the `models.role` and `models.permission` values to point to your new models.
Note the following requirements when extending/replacing the models:
### Extending
If you need to EXTEND the existing `Role` or `Permission` models note that:
- Your `Role` model needs to extend the `Spatie\Permission\Models\Role` model
- Your `Permission` model needs to extend the `Spatie\Permission\Models\Permission` model
### Replacing
If you need to REPLACE the existing `Role` or `Permission` models you need to keep the following things in mind:
- Your `Role` model needs to implement the `Spatie\Permission\Contracts\Role` contract
- Your `Permission` model needs to implement the `Spatie\Permission\Contracts\Permission` contract
## Migrations - 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.

View File

@@ -0,0 +1,8 @@
---
title: Other
weight: 8
---
Schema Diagram:
You can find a schema diagram at https://drawsql.app/templates/laravel-permission

View File

@@ -0,0 +1,92 @@
---
title: Extending PhpStorm
weight: 7
---
# Extending PhpStorm to support Blade Directives of this package
1. In PhpStorm, open Preferences, and navigate to **Languages and Frameworks -> PHP -> Blade**
(File | Settings | Languages & Frameworks | PHP | Blade)
2. Uncheck "Use default settings", then click on the `Directives` tab.
3. Add the following new directives for the laravel-permission package:
**role**
- has parameter = YES
- Prefix: `<?php if(auth()->check() && auth()->user()->hasRole(`
- Suffix: `)); ?>`
--
**endrole**
- has parameter = NO
- Prefix: blank
- Suffix: blank
--
**hasrole**
- has parameter = YES
- Prefix: `<?php if(auth()->check() && auth()->user()->hasRole(`
- Suffix: `)); ?>`
--
**endhasrole**
- has parameter = NO
- Prefix: blank
- Suffix: blank
--
**hasanyrole**
- has parameter = YES
- Prefix: `<?php if(auth()->check() && auth()->user()->hasAnyRole(`
- Suffix: `)); ?>`
--
**endhasanyrole**
- has parameter = NO
- Prefix: blank
- Suffix: blank
--
**hasallroles**
- has parameter = YES
- Prefix: `<?php if(auth()->check() && auth()->user()->hasAllRoles(`
- Suffix: `)); ?>`
--
**endhasallroles**
- has parameter = NO
- Prefix: blank
- Suffix: blank
--
**unlessrole**
- has parameter = YES
- Prefix: `<?php if(auth()->check() && !auth()->user()->hasRole(`
- Suffix: `)); ?>`
--
**endunlessrole**
- has parameter = NO
- Prefix: blank
- Suffix: blank
--

View File

@@ -0,0 +1,40 @@
---
title: Database Seeding
weight: 2
---
You may discover that it is best to flush this package's cache before seeding, to avoid cache conflict errors. This can be done directly in a seeder class. Here is a sample seeder, which first clears the cache, creates permissions and then assigns permissions to roles (the order of these steps is intentional):
```php
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class RolesAndPermissionsSeeder extends Seeder
{
public function run()
{
// Reset cached roles and permissions
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// create permissions
Permission::create(['name' => 'edit articles']);
Permission::create(['name' => 'delete articles']);
Permission::create(['name' => 'publish articles']);
Permission::create(['name' => 'unpublish articles']);
// create roles and assign created permissions
// this can be done as separate statements
$role = Role::create(['name' => 'writer']);
$role->givePermissionTo('edit articles');
// or may be done by chaining
$role = Role::create(['name' => 'moderator'])
->givePermissionTo(['publish articles', 'unpublish articles']);
$role = Role::create(['name' => 'super-admin']);
$role->givePermissionTo(Permission::all());
}
}
```

View File

@@ -0,0 +1,20 @@
---
title: Timestamps
weight: 8
---
### Excluding Timestamps from JSON
If you want to exclude timestamps from JSON output of role/permission pivots, you can extend the Role and Permission models into your own App namespace and mark the pivot as hidden:
```php
protected $hidden = ['pivot'];
```
### Adding Timestamps to Pivots
If you want to add timestamps to your pivot tables, you can do it with a few steps:
- update the tables by calling `$table->timestamps();` in a migration
- extend the Permission and Role models and add `->withTimestamps();` to the BelongsToMany relationshps for `roles()` and `permissions()`
- update your User models (wherever you use the HasRoles or HasPermissions traits) by adding `->withTimestamps();` to the BelongsToMany relationshps for `roles()` and `permissions()`

View File

@@ -0,0 +1,18 @@
---
title: UI Options
weight: 10
---
## Need a UI?
The package doesn't come with any screens out of the box, you should build that yourself. Here are some options to get you started:
- If you'd like to build your own UI, and understand the underlying logic for Gates and Roles and Users, the [Laravel 6 User Login and Management With Roles](https://www.youtube.com/watch?v=7PpJsho5aak&list=PLxFwlLOncxFLazmEPiB4N0iYc3Dwst6m4) video series by Mark Twigg of Penguin Digital gives thorough coverage to the topic, the theory, and implementation of a basic Roles system, independent of this Permissions Package.
- [Laravel Nova package by @vyuldashev for managing Roles and Permissions](https://github.com/vyuldashev/nova-permission)
- [Laravel Nova package by @paras-malhotra for managing Roles and Permissions and permissions based authorization for Nova Resources](https://github.com/insenseanalytics/laravel-nova-permission)
- [How to create a UI for managing the permissions and roles](http://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/)
- [Laravel User Management for managing users, roles, permissions, departments and authorization](https://github.com/Mekaeil/LaravelUserManagement) by [Mekaeil](https://github.com/Mekaeil)

View File

@@ -0,0 +1,18 @@
---
title: Unit testing
weight: 1
---
In your application's tests, if you are not seeding roles and permissions as part of your test `setUp()` then you may run into a chicken/egg situation where roles and permissions aren't registered with the gate (because your tests create them after that gate registration is done). Working around this is simple: In your tests simply add a `setUp()` instruction to re-register the permissions, like this:
```php
public function setUp(): void
{
// first include all the normal setUp operations
parent::setUp();
// now re-register all the roles and permissions
$this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();
}
```

View File

@@ -0,0 +1,119 @@
---
title: UUID
weight: 6
---
If you're using UUIDs or GUIDs for your User models there are a few considerations to note.
> THIS IS NOT A FULL LESSON ON HOW TO IMPLEMENT UUIDs IN YOUR APP.
Since each UUID implementation approach is different, some of these may or may not benefit you. As always, your implementation may vary.
### Migrations
You will probably want to update the `create_permission_tables.php` migration:
If your User models are using `uuid` instead of `unsignedBigInteger` then you'll need to reflect the change in the migration provided by this package. Something like this would be typical, for both `model_has_permissions` and `model_has_roles` tables:
```diff
- $table->unsignedBigInteger($columnNames['model_morph_key'])
+ $table->uuid($columnNames['model_morph_key'])
```
OPTIONAL: If you also want the roles and permissions to use a UUID for their `id` value, then you'll need to also change the id fields accordingly, and manually set the primary key. LEAVE THE FIELD NAME AS `id` unless you also change it in dozens of other places.
```diff
Schema::create($tableNames['permissions'], function (Blueprint $table) {
- $table->bigIncrements('id');
+ $table->uuid('id');
$table->string('name');
$table->string('guard_name');
$table->timestamps();
+ $table->primary('id');
});
Schema::create($tableNames['roles'], function (Blueprint $table) {
- $table->bigIncrements('id');
+ $table->uuid('id');
$table->string('name');
$table->string('guard_name');
$table->timestamps();
+ $table->primary('id');
});
Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames) {
- $table->bigIncrements('permission_id');
+ $table->uuid('permission_id');
...
Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames) {
- $table->bigIncrements('role_id');
+ $table->uuid('role_id');
...
Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) {
- $table->bigIncrements('permission_id');
- $table->bigIncrements('role_id');
+ $table->uuid('permission_id');
+ $table->uuid('role_id');
```
### Configuration (OPTIONAL)
You might want to change the pivot table field name from `model_id` to `model_uuid`, just for semantic purposes.
For this, in the configuration file edit `column_names.model_morph_key`:
- OPTIONAL: Change to `model_uuid` instead of the default `model_id`. (The default of `model_id` is shown in this snippet below. Change it to match your needs.)
'column_names' => [
/*
* Change this if you want to name the related model primary key other than
* `model_id`.
*
* For example, this would be nice if your primary keys are all UUIDs. In
* that case, name this `model_uuid`.
*/
'model_morph_key' => 'model_id',
],
- If you extend the models into your app, be sure to list those models in your configuration file. See the Extending section of the documentation and the Models section below.
### Models
If you want all the role/permission objects to have a UUID instead of an integer, you will need to Extend the default Role and Permission models into your own namespace in order to set some specific properties. (See the Extending section of the docs, where it explains requirements of Extending, as well as the configuration settings you need to update.)
- You may want to set `protected $keyType = 'string';` so Laravel handles joins as strings and doesn't cast to integer.
- OPTIONAL: If you changed the field name in your migrations, you must set `protected $primaryKey = 'uuid';` to match.
- Usually for UUID you will also set `public $incrementing = false;`. Remove it if it causes problems for you.
It is common to use a trait to handle the $keyType and $incrementing settings, as well as add a boot event trigger to ensure new records are assigned a uuid. You would `use` this trait in your User and extended Role/Permission models. An example `UuidTrait` is shown here for inspiration. Adjust to suit your needs.
```php
<?php
namespace App;
use Facades\Str;
trait UuidTrait
{
public $incrementing = false;
protected $keyType = 'string';
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = $model->{$model->getKeyName()} ?: (string) Str::orderedUuid();
});
}
}
```
### User Models
> Troubleshooting tip: In the ***Prerequisites*** section of the docs we remind you that your User model must implement the `Illuminate\Contracts\Auth\Access\Authorizable` contract so that the Gate features are made available to the User object.
In the default User model provided with Laravel, this is done by extending another model (aliased to `Authenticatable`), which extends the base Eloquent model.
However, your app's UUID implementation may need to override that in order to set some of the properties mentioned in the Models section above.
If you are running into difficulties, you may want to double-check whether your User model is doing UUIDs consistent with other parts of your app.