cubekit / laracan
该包最新版本(v0.2.1)的许可证信息不可用。
轻松定义当前用户的权限。
v0.2.1
2015-04-10 15:25 UTC
Requires
- php: >=5.4.0
- illuminate/support: 5.0.*
This package is not auto-updated.
Last update: 2024-09-28 17:49:07 UTC
README
安装
- 使用composer安装包
composer require cubekit/laracan
- 在
config/app.php
中添加提供者
'providers' => [
// ...
'Cubekit\Laracan\LaracanServiceProvider',
// ...
],
- 发布配置
php artisan vendor:publish --provider="Cubekit\Laracan\LaracanServiceProvider"
- 将
Ability
类添加到app
文件夹中并实现Cubekit\Laracan\AbilityContract
注意:默认配置假定
Ability
类位于app
文件夹中。您可以自由更改它并将类放置在您想要的位置。
用法
- 定义权限
class Ability implements AbilityContract { public function initialize($user, Closure $can) { $user = $user ?: new App\User; // NOTE: Laracan does not provide any roles behavior! Assume that some // package already installed for this, like Entrust if ($user->hasRole('admin')) { // Admin can edit posts and comments unconditionally $can('edit', 'Post'); $can('edit', 'Comment'); return; } // User can edit a post only if he is its author $can('edit', 'Post', ['author_id' => $user->getKey()]); $can('edit', 'Comment', function($comment) use ($user) { // User can edit a comment only if he is its author // and comment is not older than 15 minutes return ( $comment->author_id == $user->getKey() && $comment->created_at >= Carbon::now()->subMinutes(15) ); }); } }
- 在请求中检查权限
class EditPostRequest { public function rules() { // ... } public function authorize() { $post = Post::find( $this->route('post') ); return can('edit', $post); } }
- 在视图中检查权限
@foreach($post->comments as $comment) <div class="comment"> <div class="comment-body">{{ $comment->body }}</div> @can('edit', $comment) <div class="comment-footer"> <a href="{{ route('comment.edit', $comment) }}">Edit</a> </div> @endcan </div> </div> @endforeach
- 或者您可以直接使用
can
函数以强制IDE理解此代码
@foreach($post->comments as $comment) <div class="comment"> <div class="comment-body">{{ $comment->body }}</div> @if( can('edit', $comment) ) <div class="comment-footer"> <a href="{{ route('comment.edit', $comment) }}">Edit</a> </div> @endif </div> </div> @endforeach
许可证
MIT