标签:
1.方法一
namespace App\Providers; ... class AuthServiceProvider extends ServiceProvider { ... public function boot(GateContract $gate) { parent::registerPolicies($gate); //定义授权能力 $gate->define(‘update-post‘, function($user, $post){ return $user->id == $post->user_id; }); } }
namespace App\Http\Controllers; ... //在控制器中检验授权 class PostController extends Controller { public function show($id) { //auth()->logout(); auth()->loginUsingId(3); $post = Post::findOrFail($id); // if(Gate::denies(‘show-post‘, $post)){ // abort(403, ‘sorry, not sorry!‘); // } //$this->authorize(‘update-post‘, $post); return view(‘posts.show‘, compact(‘post‘)); } }
//在view中检验授权,如果通过才显示update链接
<h2>{{$post->title}}</h2> @can(‘update-post‘, $post) <a href=#>update</a> @endcan
2.方法二
建立policy
php artisan make:policy PostPolicy
注册
namespace App\Providers; ... class AuthServiceProvider extends ServiceProvider { protected $policies = [ // ‘App\Model‘ => ‘App\Policies\ModelPolicy‘, \App\Post::class => \App\Policies\PostPolicy::class, ];
定义类策略函数
namespace App\Policies; use App\User; use App\Post; class PostPolicy { //可以建立多个检验方法对应不同场景 public function update(User $user, Post $post) { return $user->id == $post->user_id; } }
使用方法同上。
标签:
原文地址:http://www.cnblogs.com/fenle/p/4851149.html