Laravel Scopes provides a set of reusable Eloquent global scopes to control model visibility based on user ownership and public/private status.
It is designed for easy integration with Laravel's authorization policies.
Install the package via Composer:
composer require curly-deni/laravel-scopes
All traits are located under the Aesis\Scopes\Traits namespace.
HasOwnershipScope — restricts access to models owned by the current user (user_id field required).HasPublicScope — restricts access to public models (public field required).HasPrivateScope — restricts access to private models (private field required).HasSelfScope — allows users to see their own models in addition to public/private ones (user_id field required).Use HasOwnershipScope when users should only see their own models.
use Aesis\Scopes\Traits\HasOwnershipScope;
class Post extends Model
{
use HasOwnershipScope;
}
Use HasPublicScope or HasPrivateScope to filter models by their visibility flag.
Optionally, add HasSelfScope to also allow users to see their own models.
use Aesis\Scopes\Traits\HasPublicScope;
use Aesis\Scopes\Traits\HasSelfScope;
class Post extends Model
{
use HasPublicScope, HasSelfScope;
}
| Use Case | Required Traits |
|---|---|
| Users should see only their own models | HasOwnershipScope |
| Users should see only public models | HasPublicScope |
| Users should see only private models | HasPrivateScope |
| Users should see public models and their own private models | HasPublicScope + HasSelfScope |
| Users should see private models and their own private models | HasPrivateScope + HasSelfScope |
| Trait | Required Field |
|---|---|
HasPublicScope |
public |
HasPrivateScope |
private |
HasOwnershipScope |
user_id |
HasSelfScope |
user_id |
When using scopes, you should define the following permissions in your model policies:
| Method | Purpose |
|---|---|
viewPrivate(User $user) |
Allows a user to view private models (e.g., admins or users with special roles). |
viewForeign(User $user) |
Allows a user to view other users' models (in addition to their own, if HasSelfScope is used). |
Example policy:
class PostPolicy
{
public function viewPrivate(User $user): bool
{
// Allow access to private models for admins
return $user->is_admin;
}
public function viewForeign(User $user): bool
{
// Allow users to view models owned by others
return $user->can('view-others-posts');
}
}
HasOwnershipScope cannot be combined with any other traits.HasPublicScope and HasPrivateScope cannot be used together.HasSelfScope requires either HasPublicScope or HasPrivateScope.The MIT License (MIT).
Please see the LICENSE.md file for more information.
Laravel Scopes help you automatically filter models by ownership or visibility status without writing repetitive query logic.
Combined with authorization policies, it provides flexible and secure access control at the Eloquent level.
How can I help you explore Laravel packages today?