Certainly! Here’s a solution to your Laracasts forum question, "Policies not blocking edits":
When you visit /post/3/edit, the typical mechanism in Laravel is for the controller method (usually edit()) to handle this route. However, authorization policies do not apply automatically to every controller method — you must explicitly check policy permissions when opening "edit" pages.
For view pages (/post/3), you might be using route model binding in combination with implicit policy checks (using, for example, resource controllers with authorizeResource() or authorize() middleware). For edit pages, you need to ensure authorization is also checked in your controller.
How to Protect /edit:
1. Manually Check Policy in the edit() Method
In your controller's edit method, add:
public function edit(Post $post)
{
$this->authorize('update', $post);
// Now return the edit view
return view('posts.edit', compact('post'));
}
This uses Laravel's built-in authorization to check the update function of your PostPolicy.
2. Use Controller Authorization Helpers
If you're using a resource controller, you can add authorization globally by adding this line to your controller's constructor:
public function __construct()
{
$this->authorizeResource(Post::class, 'post');
}
This will automatically apply the relevant policy methods (view, update, delete, etc.) to the resource controller's methods, including edit.
3. Use Middleware (Optional)
You can also use a middleware to check policy:
Route::get('/post/{post}/edit', [PostController::class, 'edit'])
->middleware('can:update,post');
This route middleware will ensure only authorized users can access the edit page.
Summary
Authorization policies are not automatically applied to edit routes. You need to explicitly authorize the user before showing the edit page, either inside your controller or via route middleware.
Let me know if you need a tailored code example for your specific use case!