授权用户是否可以执行某个动作
方法1:
可以通过编写Gates进行定义
在AppProvidersAuthServiceProvider文件中的boot方法中:
public function boot() { $this->registerPolicies(); Gate::define('userupdate', function ($currentUser,$model) { return $currentUser->id === $model->id; }); }
$currentUser是当前登录用户,$model是要操作的模型,通过判断当前用户模型以及要操作的模型的id是否相等,来授权用户是否能进行某一步的操作
控制器使用
$bool = Gate::allows('userupdate', $user);//如果两者的id相等$bool为true,否则为false,如果使用Gate::authorize('update', $post);没有权限时抛出异常,http响应报错
具体其它的操作方法可以在laravel文档中查看https://learnku.com/docs/laravel/6.x/authorization/5153
方法二:
创建策略
生成策略
php artisan make:policy PostPolicy //生成的策略将放在 app/Policies 目录
生成策略后就要注册:
注册一个策略将指导 Laravel 在授权针对给定模型的操作时使用哪个策略:
<?php
namespace AppProviders;
use AppPost;
use AppPoliciesPostPolicy;
use IlluminateSupportFacadesGate;
use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* 应用程序的策略映射。
*
* @var array
*/
protected $policies = [
Post::class => PostPolicy::class,//post模型对应post策略
];
/**
* 注册任何应用程序 authentication / authorization 服务。
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
也可以使用自动注册策略:
<?php namespace AppProviders; . . . class AuthServiceProvider extends ServiceProvider { . . . public function boot() { $this->registerPolicies(); // 修改策略自动发现的逻辑 Gate::guessPolicyNamesUsing(function ($modelClass) { // 动态返回模型对应的策略名称,如:// 'AppModelsUser' => 'AppPoliciesUserPolicy', return 'AppPolicies\'.class_basename($modelClass).'Policy'; }); } }
//这里的模型都是放在AppModels目录
编写策略:
<?php
namespace AppPolicies;
use AppUser;
use AppPost;
class PostPolicy
{
/**
* 确定用户是否可以更新给定的帖子。
*
* @param AppUser $user
* @param AppPost $post
* @return bool
*/
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
控制器使用策略:
<?php
namespace AppHttpControllers;
use AppPost;
use IlluminateHttpRequest;
use AppHttpControllersController;
class PostController extends Controller
{
/**
* 更新指定博客帖子。
*
* @param Request $request
* @param Post $post
* @return Response
* @throws IlluminateAuthAccessAuthorizationException
*/
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);//也可以使用Gate::authorize('update', $post);
//如果使用以上两个都报错this action is unauthorized,那就使用方法一
// 当前用户可以更新博客....
}
}