Laravel Policy: A Simple Guide

When building a Laravel application, you often need to control who can perform certain actions. For example, only the author of a blog post should be able to edit or delete it.

Laravel provides Policies to handle this authorization logic in a clean and organized way.

What is a Policy?

A Policy is a class that contains authorization rules for a specific model.

Instead of writing permission checks inside your controllers, you keep them in a policy class. This makes your code cleaner and easier to maintain.

When Should You Use a Policy?

Use a policy when authorization is related to a model.

Examples:

  • Can a user edit a post?
  • Can a user delete a comment?
  • Can a user update their profile?

If the permission is about a specific model, a policy is usually the best choice.

Creating a Policy

Suppose you have a Post model.

Create a policy using:

php artisan make:policy PostPolicy --model=Post

Laravel creates a PostPolicy class inside the app/Policies folder.

Example

Imagine only the owner of a post can update it.

// app/Policies/PostPolicy.php

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

This method returns:

  • true if the logged-in user owns the post.
  • false otherwise.

Using the Policy

Inside your controller:

public function edit(Post $post)
{
    $this->authorize('update', $post);

    return view('posts.edit', compact('post'));
}

If the user is authorized, Laravel continues to the next line.

If not, Laravel automatically returns a 403 Forbidden response.

Why Use Policies?

  • Keeps controllers clean.
  • Stores authorization logic in one place.
  • Makes code easier to read and maintain.
  • Works well for CRUD operations (Create, Read, Update, Delete).

Conclusion

Policies are Laravel’s recommended way to handle model-based authorization.

A good rule to remember is:

  • Gates → Simple authorization checks.
  • Policies → Authorization related to models.

If your application has models like Post, Comment, or Product, using policies will make your code more organized and easier to manage.