sowailem/ownable
Automate ownership across Eloquent models without traits. Register ownable models via config or API, manage owners with the Owner facade, track ownership history, and auto-inject ownership data into JSON responses via middleware. Includes built-in routes and @owns directive.
Install via Composer: composer require sowailem/ownable. The package adds an Ownable trait to models that enforces ownership at the database level using owner_type and owner_id columns (polymorphic relationship). Begin by adding the trait to any model requiring ownership control, then run php artisan migrate — the package ships with a migration that adds the required columns to your tables (now following Laravel naming conventions as of v1.0.6). The first use case is typically protecting resource updates/deletes: only the assigned owner (e.g., User) should be allowed to modify their own records. Additionally, v1.0.6 introduces the @owns Blade directive for clean ownership-based template conditionals.
$user->can('update', $model) — the trait automatically scopes queries via whereBelongsToUser($user) helper methods (e.g., Post::whereBelongsToUser($user)->get()).->owner() or assign owner_id before saving (e.g., $post->owner()->associate($user)). Use middleware or policy before/after hooks to enforce this consistently.owner_type polymorphic field to support different owner models like Team, Organization, or User — query with ->ownedBy($ownerModel) to filter across owner types.SoftDeletes; deleted records are still scoped by owner, ensuring no leakage across users’ soft-deleted items.@owns directive to conditionally render content based on ownership:
@owns($post)
<button>Edit Post</button>
@endowns
This internally calls $post->isOwnedBy(auth()->user()) and is especially useful for layout-level access control.ownedBy($owner) or whereBelongsTo($user); forgetting this can leak data in public endpoints.owner_id is stored as string (not unsignedBigInteger) — configure via config/ownable.php or override the trait’s getOwnerIdColumn() method.owner_id; use ->for($user) in factories or set ->owner()->associate($user) explicitly in test fixtures.owner_type + owner_id) can cause slowdowns on large tables; consider adding composite index ['owner_type', owner_id]` manually if needed.isOwnedBy($user) for custom logic (e.g., admin bypass), or extend OwnableServiceProvider to register global scopes.OwnerContract is now properly imported — if you’ve implemented custom traits or extensions, ensure use Sowailem\Ownable\Contracts\OwnerContract; is included.How can I help you explore Laravel packages today?