Policies — Model-Based Authorization
Policies organize authorization logic around a specific model. Each policy method corresponds to a controller action (viewAny, view, create, update, delete). Policies are the recommended approach for model-based authorization — cleaner than gates for CRUD operations.
Creating and Using Policies
// php artisan make:policy PostPolicy --model=Post
class PostPolicy
{
public function viewAny(User $user): bool
{
return true; // Everyone can view posts
}
public function view(User $user, Post $post): bool
{
return $post->published || $user->id === $post->user_id;
}
public function create(User $user): bool
{
return true; // Any authenticated user
}
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id || $user->isAdmin();
}
}
// Using in controllers
public function update(Request $request, Post $post)
{
$this->authorize('update', $post); // 403 if unauthorized
$post->update($request->validated());
return redirect()->route('posts.show', $post);
}
// Blade
@can('update', $post)
<a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcanTip
Tip
Practice Policies ModelBased Authorization in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Policies for models, Gates for simple.
Practice Task
Note
Practice Task — (1) Write a working example of Policies ModelBased Authorization from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Policies ModelBased Authorization is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.