在Laravel中为我们提供了一种简单的方式来处理用户授权动作,主要有两种方式Gates和Policy(策略),但这两种方法默认是认证User模型的信息,我们想使授权认证为后台用户Admin模型的信息需进行如下操作
1.参照我的另一篇文章【多表用户登录认证】增加一个使用auth登录的后台用户
2.在要认证的路由绑定中间件
Route::get('mydel','Procontroller@mydel')->middleware('auth:admin')->
到此Gate就会默认获取到后台用户的信息,你可以进行相应的权限判断
下面是一个非常简单的示例
<?php
namespace App\Policies;
use App\User;
use App\Admin;
use App\Root;
use Auth;
use Illuminate\Auth\Access\HandlesAuthorization;
class DelPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the admin.
*
* @param \App\User $user
* @param \App\Admin $admin
* @return mixed
*/
/**
* Determine whether the user can update the admin.
*
* @param \App\User $user
* @param \App\Admin $admin
* @return mixed
*/
public function update(Admin $user)
{
return Admin::find(Auth::id())->roots->del;
//返回用户是否有删除权限
// return true;/
}
/**
* Determine whether the user can delete the admin.
*
* @param \App\User $user
* @param \App\Admin $admin
* @return mixed
*/
}
//如果用户有删除权限
if($this->authorize('update',Root::class)){
dump('可以');
}
模板中使用
@can('update',App\Root::class)
有更新权限的视图
@endcan
@cannot('update',App\Root::class)
没有更新权限
@endcan
通过中间件认证