Laravel Gate&Policy 权限管理

23 篇文章 0 订阅
20 篇文章 0 订阅

其实很简单,就是两步:定制权限、判断权限。

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值