Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

laravelio/laravel.io

2497 stars
3 code files
View laravelio/laravel.io on GitHub

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;
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.