How do I define policies for Eloquent models?
Jun 20, 2025 am 12:15 AMTo define and use policies in Laravel's Eloquent ORM effectively, follow these steps: 1. Create a policy class using the Artisan command php artisan make:policy PostPolicy --model=Post to generate a model-specific or standalone policy. 2. Register the policy in AuthServiceProvider.php by mapping the model to its policy inside the $policies array. 3. Define authorization methods like update, view, or delete in the policy class, each accepting a User and optionally a model instance to enforce rules such as ownership checks. 4. Enforce policies in controllers via $this->authorize(), in middleware using can:update,post, or in Blade templates with @can directives, ensuring clean, maintainable, and consistent access control throughout your application.
When working with Laravel's Eloquent ORM, defining policies helps you manage authorization logic in a clean and organized way. The main idea is to separate access control from your controllers by using dedicated policy classes.
Here’s how you can define and use policies for Eloquent models effectively.
1. Create a Policy Class
The first step is to generate a policy class. Laravel provides an Artisan command that makes this easy:
php artisan make:policy PostPolicy --model=Post
This creates a PostPolicy
class inside the app/Policies
directory and automatically binds it to the Post
model.
If you want a standalone policy (not tied to a specific model), just omit the --model
option.
Tip: Make sure the Policies
directory exists under app
. If not, create it manually.
2. Register Policies in the Service Provider
Once created, you need to register your policy so Laravel knows which model it belongs to.
Open AppServiceProvider.php
(or better yet, a dedicated service provider like AuthServiceProvider.php
) and add the mapping inside the boot()
method:
use App\Models\Post; use App\Policies\PostPolicy; protected $policies = [ Post::class => PostPolicy::class, ];
This tells Laravel to use PostPolicy
when checking permissions for the Post
model.
Important: Don’t forget to import both the model and the policy at the top of the file.
3. Define Authorization Rules Inside the Policy
Each method in your policy corresponds to an action — like view
, create
, update
, or delete
.
Here’s what a basic PostPolicy
might look like:
public function update(User $user, Post $post) { return $user->id === $post->user_id; }
This means only the user who owns the post can edit it.
You can also define a before
method in your policy for global checks — like allowing admins to do anything before individual rules are evaluated.
4. Use Policies in Your Application
Now that your policy is set up, you can check permissions in several ways:
- In Controllers (Recommended):
$post = Post::findOrFail($id); $this->authorize('update', $post);
- In Middleware:
Route::put('/posts/{post}', function (Post $post) { // Logic here })->middleware('can:update,post');
- In Blade Templates:
@can('update', $post) <button>Edit</button> @endcan
These methods keep your views and controllers clean while enforcing consistent access rules.
Final Notes
Setting up policies takes a few steps, but once they're in place, managing authorization becomes much easier and scalable. It’s especially helpful as your app grows and you have more roles and conditions to handle.
Make sure to name your policy methods clearly and keep related logic grouped together. Also, don’t forget to test different user roles to ensure your rules behave as expected.
That’s basically it. Not too bad once you get the hang of it.
The above is the detailed content of How do I define policies for Eloquent models?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article brings you relevant knowledge about Laravel. It mainly introduces to you the implementation of optimistic locking in the Laravel Eloquent model. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to you.

Key points of price strategy and promotion design in PHP flash sale system In a flash sale system, price strategy and promotion design are very important parts. Reasonable price strategies and well-designed promotions can attract users to participate in flash sale activities and improve the user experience and profitability of the system. The following will introduce the key points of price strategy and promotional activity design in the PHP flash sale system in detail, and provide specific code examples. 1. Key points in price strategy design: Determine the benchmark price: In the flash sale system, the benchmark price refers to the price of the product when it is normally sold. exist

Laravel development: How to use LaravelEloquent to implement polymorphic associations? Polymorphic association is an important feature of Laravel Eloquent, which allows one model to establish relationships with multiple different models. In practical applications, processing different types of data is relatively simple and efficient, especially in database design. In this article, we will discuss how to implement polymorphic associations using Laravel Eloquent. 1. What is a polymorphic association? Polymorphism

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

EXE to PHP: An effective strategy to achieve function expansion. With the development of the Internet, more and more applications have begun to migrate to the web to achieve wider user access and more convenient operations. In this process, the demand for converting functions originally run as EXE (executable files) into PHP scripts is also gradually increasing. This article will discuss how to convert EXE to PHP to achieve functional expansion, and give specific code examples. Why Convert EXE to PHP Cross-Platformness: PHP is a cross-platform language

Converting an array into an object using Eloquent in Laravel requires the following steps: Create an Eloquent model. Use Eloquent's select method to get the result and convert it to an array. Use ArrayObject to convert an array into an object. Gets an object property to access an array's values.

MyBatis cache strategy analysis: best practices for first-level cache and second-level cache When developing using MyBatis, we often need to consider the choice of cache strategy. The cache in MyBatis is mainly divided into two types: first-level cache and second-level cache. The first-level cache is a SqlSession-level cache, while the second-level cache is a Mapper-level cache. In practical applications, rational use of these two caches is an important means to improve system performance. This article will use specific code examples to analyze a MyBatis

PHPCMS user name security setting strategy revealed In website development, user account security has always been an aspect that developers attach great importance to. The security settings of the username are also crucial, because the username is not only the user's login credentials, but may also expose the user's personal information and even cause security risks. This article will reveal the username security setting strategy in PHPCMS and give specific code examples for developers to refer to. 1. Prevent common usernames. In order to improve the security of usernames, developers should prevent users from using excessive
