Gates and policies
Define gates
Gates are small closures that answer one question: may this user do this action. Define them near boot with the user and the target model as inputs.
Return true or false and keep the rule readable in one short line.
use Illuminate\Support\Facades\Gate; Gate::define("edit-post", function ($user, $post) { return $user->id === $post->user_id; });
A Policy class
Policies group all rules for one model in a single class. Each method matches an action like view or update.
Generate the class with artisan and link it to the model it guards.
php artisan make:policy PostPolicy
INFO Policy [app/Policies/PostPolicy.php] created successfully.
public function update($user, $post) { return $user->id === $post->user_id; }
Authorize in controllers
Controllers enforce the rule before touching data. Authorize names the action and passes the model, then stops the request on failure.
Place the call first so denied users never reach the update logic.
$this->authorize("update", $post);
Check in Blade
Views should hide buttons the user may not press. The can directive wraps any markup that needs permission.
Users without the right see plain text instead of a dead button.
@can("update", $post) <button type="submit">Save</button> @endcan
Next: Notifications
Article author: Arthur Isaev