An Introduction to Laravel Policy
An Introduction to Laravel Policy
30 Dec 2018 . Laravel. 7.6K views
If you heard about Laravel Policy and still not yet use that, this introduction to Laravel Policy post is for you then. In this tutorial, I will write a real-life tutorial that, how to use Laravel Policy for the beginner.
What is Laravel Policy
Laravel policy is a part of Authorization of Laravel that help you to protect content or resources from unauthorized access.
Just imagine a simple concept that you have a blog that contains users and posts. Normally the post can be visible to every visitor, however, to edit a post, you need to be the owner of the post. In this tutorial, I will show you how to show the edit post option to the post owner only.
The basic concept of this apps is-
- A user can create a post
- A post can be viewed by visitor / user
- The post creator only can edit the post
- The post creator only can able to delete
Basic Configuration
First, let's connect with Database. In your .env file, update like follow. My database name is laravel-policy.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-policy
DB_USERNAME=root
DB_PASSWORD=
Next, need to create the migration, model and controller for posts and users table.
php artisan make:model User -m -c
php artisan make:model Post -m -c
Let's define migration now.
User
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Post
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('deatils');
$table->integer('user_id');
$table->integer('flag');
$table->timestamps();
});
Once, you have done this part, now run the migration.
php artisan migrate
If everything goes smoothly, you will see two tables in your database called users and posts. Now you may record data in your tables. You may go for seeding data or add manually. To keep this tutorial show, I just skip this step.
Create Policy
The ideal way to define a policy is to follow the model name. In our case, our model name is Post, so that our policy name should be PostPolicy to the authorized user to edit or delete. The artisan command to do that is-
php artisan make:policy PostPolicy
This command make:policy will generate an empty policy class in the App\Policies folder. In addition, you can suffix --model=Post to create CRUD.
Writing Policy
Now, let write the policy for the post where the post id is 1 that belongs to a user who's id is 1. So, the post is available to view from any user or visitor, however, in order to update or delete, you need to be a user who's id is 1.
Now, defining the update method to restrict the update option from mass people.
<?php
namespace App\Policies;
use App\User;
use App\Post;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine if the given post can be updated by the user.
*
* @param \App\User $user
* @param \App\Post $post
* @return bool
*/
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}
This update method will check whether the post creator is this user or not. It will return true once it matches otherwise, returns false.
Registering a Policy.
Once you have defined policy, you need to register the policy in the app/Providers/AuthServiceProvider.
<?php
namespace App\Providers;
use App\Post;
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Post::class => PostPolicy::class
];
}
How to use
Once you are in this stage that means, you have done everything successfully. Now, you need to use that.
Via View
In the view, you can use @can and @cannot directive.
@can('update', $post)
<!-- The Current User Can Update The Post -->
@endcan
@cannot('update', $post)
<!-- The Current User Can't Update The Post -->
@endcannot
Via Model
In the model, you can use in the following way-
if ($user->can('update', $post)) {
//
}
Via Controller
Even you can use via controller also. Cool, right?
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
// The current user can update the blog post...
}
Sweet. Hope, you will like this. If you love this, feel free to share.
You can get this code in the following repository. https://github.com/laravel-school/introduction-laravel-policy
Thank you.
An Introduction to Laravel Policy的更多相关文章
- A Quick Introduction to Linux Policy Routing
A Quick Introduction to Linux Policy Routing 29 May 2013 In this post, I’m going to introduce you to ...
- Laravel policy 的应用
Laravel 提供更简单的方式来处理用户授权动作.类似用户认证,有 2 种主要方式来实现用户授权:gates 和策略,我这里主要讲解下策略的使用. 文档 上面有详细的说明,我这里只根据自己使用过程做 ...
- 使用 Laravel 实现微型博客系统
参考链接:An Introduction to Laravel Authorization Gates 这个微型博客系统包含两个用户角色(作者 和 编辑),它们的权限如下: 作者能创建博客 作者能更新 ...
- PHP and laravel知识点小小积累
function () use ($x, &$y){} 自从PHP5.3开始有了closure/匿名函数的概念,在这里的use关键词的作用是允许匿名函数capture到父函数scope 内存在 ...
- Laravel Gate 授权方式的使用指南
参考链接:An Introduction to Laravel Authorization Gates 本文使用 Laravel 的 Gate 授权方式 实现一个基于用户角色的博客发布系统. 在系统包 ...
- Laravel 5.8: Automatic Policy Resolution
Laravel 5.8: Automatic Policy Resolution March 26, 2019 One of the new features in Laravel 5.8 allow ...
- Laravel策略(Policy)示例
场景:当前用户创建的订单,只能当前用户自己看,可以通过授权策略类(Policy)来实现 1.php artisan make:policy OrderPolicy 成功后,默认只有一个构造方法.因为涉 ...
- laravel/lumen 单元测试
Testing Introduction Application Testing Interacting With Your Application Testing JSON APIs Session ...
- Machine Learning Algorithms Study Notes(1)--Introduction
Machine Learning Algorithms Study Notes 高雪松 @雪松Cedro Microsoft MVP 目 录 1 Introduction 1 1.1 ...
随机推荐
- diy操作系统 0:万事开头难
许久之前就有写一个tiny的操作系统的打算,但时间和精力关系,想法一直没有成为最终的代码.操作系统的构建本身是个系统工程,门槛较高,需要多方面的知识,往往几行代码背后是厚厚的几本书才能说清 ...
- 【数据结构】Tournament Chart
Tournament Chart 题目描述 In 21XX, an annual programming contest, Japan Algorithmist GrandPrix (JAG) has ...
- 深度剖析Kubernetes API Server三部曲 - part 3
在本系列的前两部分中我们介绍了API Server的总体流程,以及API对象如何存储到etcd中.在本文中我们将探讨如何扩展API资源. 在一开始的时候,扩展API资源的唯一方法是扩展相关API源代码 ...
- Mysql分表和分区的区别、分库和分表区别
一,什么是mysql分表,分区 什么是分表,从表面意思上看呢,就是把一张表分成N多个小表,具体请看:mysql分表的3种方法. 什么是分区,分区呢就是把一张表的数据分成N多个区块,这些区块可以在同一个 ...
- css 清除浮动 & BFC
前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 文档流的概念:html 中 block 块元素默认是单独占据一行的,从上到下排列,也就是我们说的文档流. ...
- SpringMVC 出现 406(Not Acceptable)
首先,需要清楚,http state 406代表什么意思: 406是HTTP协议状态码的一种,表示无法使用请求的特性来响应请求的网页.一般指客户端浏览器不接受所请求页面的MIME类型. 出现这样的错误 ...
- C#项目中窗体的ShowDialog()和show()的区别
ShowDialog()弹出的窗体为模式化窗体: show()弹出的窗体为非模式化窗体: 模式化窗体与非模式化窗体的区别: 模式化窗体会使程序中断,直到关闭窗体: 打开窗体后不能替换到其他窗体: 子窗 ...
- JDBC 学习复习6 学习与编写数据库连接池
之前的工具类DBUtil暴露的问题 用户每次请求都需要向数据库获得链接,而数据库创建连接通常需要消耗相对较大的资源,创建时间也较长.假设网站一天10万访问量,数据库服务器就需要创建10万次连接,极大的 ...
- Cause: com.mysql.jdbc.PacketTooBigException: Packet for query is too large (16944839 > 16777216). You can change this value on the server by setting the max_allowed_packet' variable.
今天发现task微服务的error日志报如下错误: Cause: com.mysql.jdbc.PacketTooBigException: Packet for query is too large ...
- 转:基于Maven管理的JavaWeb项目目录结构参考
通常在创建JavaWeb项目时多多少少都会遵循一些既定的比较通用的目录结构,下面分享一张基于Maven管理的JavaWeb项目目录结构参考图: 上图仅是参考,不同项目不同团队都有自己的约定和规范. 个 ...