其实很简单,就是两步:定制权限、判断权限。
Gate闭包方式定义权限
public function boot()
{
$this->registerPolicies();
Cate::define('update_post',funtion($user,$post){
return $user->id==$post->user_id;
});
}
用Policy方法定义权限:
public function boot()
{
$this->registerPolicies();
Cate::define('update_post',App\Policies\PostPolicy@update');
}
控制器中判定权限:
if(Gate::allows('update-post',$post)){
//
}
模板中判定权限:
@can('update',$post)
//
@elscan('create',App\Post::class)
//
endcan
实践1(闭包):
定义权限:
app/Providers/AuthServiceProvider.php
use Illuminate\Support\Facades\Auth;
.....
public function boot()
{
$this->registerPolicies();
Gate::define('access-admin',function (){
if(Auth::user()->role==='admin'){
return true;
}
else{
return false;
}
});
....
或为这样就好:
use Illuminate\Support\Facades\Auth;
.....
public function boot()
{
$this->registerPolicies();
Gate::define('access-admin',function (){
return Auth::user()->role==='admin';
});
}
....
路由web.php:
Route::get('/accesstoadmin',function (){
if(Gate::allows('access-admin',Auth::user())){ //这里的第二参照Auth::user() 其实不需要
return view('admin');
}
abort(404);
});
模板中判断:
@can('access-admin',Auth::user())
<li>
<a href="{{ route('admin') }}"><span >管理中心</span></a>
</li>
@endcan
实践2(Policy):
php artisan make:policy AdminPolicy
app/policies/AdminPolicy.php
...
use Illuminate\Support\Facades\Auth;
.....
public function access_admin() //默认传递了user参数,若有传参,接受参数强制从第2个开始;$user,$messages....
{
return Auth::user()->role==='admin';
}
app/Providers/AuthServiceProvider.php
..
use Illuminate\Support\Facades\Gate;
...
public function boot()
{
$this->registerPolicies();
Gate::define('access-admin','App\Policies\AdminPolicy@access_admin');
}
php artisan make:controll AdminControll
控制器app/Http/Controllers/AdminController.php
use Illuminate\Support\Facades\Gate;
.......
public function access_admin()
{
if(Gate::allows('access-admin')){
return view('admin');
}
return "404";
}
路由web.php
Route::get('/testadmin','AdminController@access_admin')->name('admin');
控制器推荐方法:
public function access_admin()
{
$this->authorize('access-admin');
return view('admin');
}
只要验证不通过,laravel会自动抛出一个HttpException This action is unauthorized.