## 定义授权
路径:app/Policies
示例:
**定义授权**
app/Policies/BlockPolicy.php
```php
namespace App\Policies;
use App\Models\User;
use App\Models\Block;
/**
* 区块授权策略
*
* Class BlockPolicy
* @package Wanglelecc\Laracms\Policies
*/
class BlockPolicy extends Policy
{
public function index(User $user, Block $block)
{
return $user->can('manage_block');
}
public function create(User $user, Block $block)
{
return false;
}
public function update(User $user, Block $block)
{
return $user->can('manage_block');
}
public function destroy(User $user, Block $block)
{
return false;
}
}
```
> 可通过 Laravel 提供的 `php artisan make:policy` 自动生成;检查的权限节点需要预先添加。
**注册授权**
在 `AuthServiceProvider` 服务提供者的 policies 属性中:
```php
.
.
.
protected $policies = [
.
.
.
\App\Models\Block::class => \App\Policies\BlockPolicy::class,
.
.
.
]
.
.
.
```
**使用授权**
一般在控制器中使用
BlocksController:
```php
.
.
.
public function create(Block $block, Request $request){
# 调用授权
$this->authorize('create', $block);
$type = config('blocks.types.'.$request->type) ? $request->type : '';
return backend_view('blocks.create_and_edit', compact('block', 'type'));
}
.
.
.
```