-
app/Policies/ArticlePolicy.php
Open in GitHub// You generate such file with Artisan command "php artisan make:policy ArticlePolicy" // In each method, you automatically get the User object from the session // Each method should return TRUE or FALSE // Also, you may accept more parameters, which you would need to pass when checking final class ArticlePolicy { const UPDATE = 'update'; const DELETE = 'delete'; const APPROVE = 'approve'; const DISAPPROVE = 'disapprove'; const PINNED = 'togglePinnedStatus'; public function update(User $user, Article $article): bool { return $article->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin(); } public function delete(User $user, Article $article): bool { return $article->isAuthoredBy($user) || $user->isModerator() || $user->isAdmin(); } public function approve(User $user, Article $article): bool { return $user->isModerator() || $user->isAdmin(); } public function disapprove(User $user, Article $article): bool { return $user->isModerator() || $user->isAdmin(); } }
-
app/Http/Controllers/Admin/ArticlesController.php
Open in GitHub// To use the policy, just call $this->authorize() from the Controller use App\Policies\ArticlePolicy; class ArticlesController extends Controller { public function approve(Article $article) { $this->authorize(ArticlePolicy::APPROVE, $article); $this->dispatchNow(new ApproveArticle($article)); // ... other method code } }
-
app/Models/User.php
Open in GitHub// Functions like $user->isModerator() come from the User model final class User extends Authenticatable implements MustVerifyEmail { const DEFAULT = 1; const MODERATOR = 2; const ADMIN = 3; public function type(): int { return (int) $this->type; } public function isModerator(): bool { return $this->type() === self::MODERATOR; } public function isAdmin(): bool { return $this->type() === self::ADMIN; } }