Laravel 5.8: Automatic Policy Resolution

March 26, 2019

One of the new features in Laravel 5.8 allows you to not register your policies in AuthServiceProvider, they will be “guessed” automatically. Here’s how it works.

Let’s remember how Policies work in general.

Step 1: Create a policy with artisan command, attaching it to a model.

php artisan make:policy PostPolicy --model=Post

Step 2. Fill in the policy with exact methods and rules

use App\User;
use App\Post; class PostPolicy
{
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}

Step 3. Register policies (this is needed only before Laravel 5.8)

use App\Post;
use App\Policies\PostPolicy; class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Post::class => PostPolicy::class,
];

So, from Laravel 5.8 you don’t need to do step 3, system will recognize the policies automatically.

Here’s how that “guessing” function actually looks in Laravel internals:

protected function guessPolicyName($class)
{
return dirname(str_replace('\\', '/', $class)).'\\Policies\\'.class_basename($class).'Policy';
}

So your Policy should be in app/Policies folder and has the same name as model, with Policy suffix.

Correct location: app/User.php -> app/Policies/UserPolicy.php

Incorrect location: app/Models/User.php -> app/Policies/UserPolicy.php

Also incorrect: app/User.php -> app/Policies/UsersPolicy.php (Users)

And, also incorrect: app/User.php -> app/Policies/User.php (should be UserPolicy.php)

If your policies and models are in “nonconventional locations” (like not in app/ or app/Policies folders, as shown above), then you may use the same $policies array in AuthServiceProvider, or specify your own logic of “guessing”:

Gate::guessPolicyNamesUsing(function ($class) {
// Do stuff
return $policyClass;
});

Here’s a link to the original commit in Laravel.

最新文章

  1. python 基本语法
  2. oracle中时间运算
  3. Coursera台大机器学习课程笔记3 – 机器学习的可能性
  4. Nginx简介
  5. 虚拟机IP设置
  6. JAVA多线程学习--哲学家就餐问题
  7. textbox不支持Ctrl+A
  8. 如何参与一个GitHub开源项目
  9. Android中Handler使用浅析
  10. JavaScrip:Function函数编程
  11. easyui datagrid使用按钮
  12. python经典书籍推荐:python编码规范
  13. 听说https更安全
  14. iOS 图像处理(一):获取某一点位置的像素
  15. ["1", "2", "3"].map(parseInt) 为何返回[1,NaN,NaN]
  16. 不同ContentType的post请求
  17. 2018 ACM-ICPC 中国大学生程序设计竞赛线上赛 H题 Rock Paper Scissors Lizard Spock.(FFT字符串匹配)
  18. Windows域的相关操作
  19. 【期望DP】BZOJ4008- [HNOI2015]亚瑟王
  20. HTML布局四剑客-Flex,Grid,Table,Float

热门文章

  1. C++ std::string 在一个字符串前插入一个字符串几种方式
  2. 03 HttpServletRequest_HttpServletResponse
  3. mysql5.7主主(双主)复制
  4. jacascript Date 学习
  5. hdu 6216 A Cubic number and A Cubic Number
  6. .net core mvc + mysql dbfirst 生成 ado.net 数据模型
  7. HTTP method GET is not supported by this URL
  8. 一:项目简介(node express vue elementui axios)
  9. epoll、mysql概念及简单操作
  10. Java 面向对象(三)static 关键字