PHPackages                             dibakar/laravel-ownership - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. dibakar/laravel-ownership

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

dibakar/laravel-ownership
=========================

Flexible ownership management package for Laravel with single &amp; multiple ownership support. with traits, scopes, and policies.

v1.0.1(6mo ago)22MITPHPPHP ^8.1

Since Sep 5Pushed 6mo agoCompare

[ Source](https://github.com/dibakarmitra/laravel-ownership)[ Packagist](https://packagist.org/packages/dibakar/laravel-ownership)[ RSS](/packages/dibakar-laravel-ownership/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (4)Versions (4)Used By (0)

Laravel Ownership
=================

[](#laravel-ownership)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d83fd061db3af541d33abfc7b66e6c4b8c1d907e5038781b08ac6197d3d7082a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646962616b61722f6c61726176656c2d6f776e6572736869702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dibakar/laravel-ownership)[![Total Downloads](https://camo.githubusercontent.com/493f14a3e24e2aed124f4283a1a502c21c54b594a29e1cb611d2d226f934fd70/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646962616b61722f6c61726176656c2d6f776e6572736869702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dibakar/laravel-ownership)[![PHP Version](https://camo.githubusercontent.com/bca14d56fb524001b71c96d3db24a28a84d34a6a9a75bbdadeb3966439d4d21d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f646962616b61722f6c61726176656c2d6f776e6572736869702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dibakar/laravel-ownership)[![License](https://camo.githubusercontent.com/3267f64e7b6fad4b5afe1d5a414d6abd97a1d58e3d84eecd487b3d7563ae1e4a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f646962616b61722f6c61726176656c2d6f776e6572736869703f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dibakar/laravel-ownership)[![StyleCI](https://camo.githubusercontent.com/100a8dc8cae298a9d5e21852a755d5a541d1178079fa402c4e8e95674b7cce79/68747470733a2f2f6769746875622e7374796c6563692e696f2f7265706f732f313035303939323833362f736869656c643f6272616e63683d6d61696e)](https://github.styleci.io/repos/1050992836)

A comprehensive ownership management system for Laravel applications. This package provides an elegant way to handle both single and multiple ownership scenarios with role-based permissions, events, and query scopes.

Features
--------

[](#features)

- **Dual Ownership Modes**: Support for both single and multiple ownership models
- **Role-based Access Control**: Define custom roles with specific permissions
- **Flexible Configuration**: Highly customizable to fit any application needs
- **Event-driven Architecture**: Built-in events for all ownership changes
- **Powerful Query Scopes**: Filter models by ownership with ease
- **Performance Optimized**: Built-in caching for ownership checks
- **Type Safety**: Strict type declarations and modern PHP features
- **Laravel Integration**: Seamless integration with Laravel's authentication system
- **Morphable Owners**: Support for any model as an owner
- **Bulk Operations**: Manage multiple owners at once with sync methods
- **Bidirectional Relationships**: Both owners and ownable models have access to each other

Installation
------------

[](#installation)

1. Install the package via Composer:

```
composer require dibakar/laravel-ownership
```

2. Publish the configuration file:

```
php artisan vendor:publish --provider="Dibakar\\Ownership\\OwnershipServiceProvider" --tag=config
```

3. Publish and run the migrations:

```
php artisan vendor:publish --provider="Dibakar\\Ownership\\OwnershipServiceProvider" --tag=migrations
php artisan migrate
```

IsOwner Trait Methods
---------------------

[](#isowner-trait-methods)

### Check Ownership

[](#check-ownership)

```
// Check if the user owns a document
$user->owns($document);

// Check if the user owns a document with a specific role
$user->owns($document, 'admin');
```

### Get Owned Items

[](#get-owned-items)

```
// Get all documents owned by the user
$documents = $user->getOwnedItems(Document::class);

// Get all documents where user has a specific role
$adminDocuments = $user->getOwnedItems(Document::class, 'admin');
```

### Transfer Ownership

[](#transfer-ownership)

```
// Transfer all documents to another user
$user->transferOwnershipTo($newUser);

// Transfer only specific type of items
$user->transferOwnershipTo($newUser, Document::class);
```

### Count Owned Items

[](#count-owned-items)

```
// Count all owned items
$count = $user->countOwnedItems();

// Count items of a specific type
$docCount = $user->countOwnedItems(Document::class);

// Count items with a specific role
$adminDocCount = $user->countOwnedItems(Document::class, 'admin');
```

### Ownership Relationship

[](#ownership-relationship)

```
// Get all ownership records
$ownerships = $user->ownerships;

// Get all owned items through the relationship
$items = $user->ownerships->map->ownable;
```

Configuration
-------------

[](#configuration)

The configuration file (`config/ownership.php`) allows you to customize various aspects of the package. Here are the main configuration options:

```
return [
    /*
    |--------------------------------------------------------------------------
    | Morph Name
    |--------------------------------------------------------------------------
    |
    | This is the name of the polymorphic relationship used for ownership.
    | You can change this to 'user', 'team', 'organization', etc.
    */
    'morph_name' => 'owner',

    /*
    |--------------------------------------------------------------------------
    | Global Scope
    |--------------------------------------------------------------------------
    |
    | When enabled, a global scope will be applied to automatically scope
    | queries to the current owner in single ownership mode.
    */
    'apply_global_scope' => true,

    /*
    |--------------------------------------------------------------------------
    | Authentication Guard
    |--------------------------------------------------------------------------
    |
    | The authentication guard used to retrieve the currently authenticated user.
    */
    'guard' => 'web',

    /*
    |--------------------------------------------------------------------------
    | Ownership Mode
    |--------------------------------------------------------------------------
    |
    | Set to 'single' for one owner per model or 'multiple' for many owners.
    */
    'mode' => 'single',

    /*
    |--------------------------------------------------------------------------
    | Cache Configuration
    |--------------------------------------------------------------------------
    */
    'cache' => [
        'enabled' => true,
        'ttl' => 3600, // Cache time-to-live in seconds
    ],

    /*
    |--------------------------------------------------------------------------
    | Multiple Ownership Configuration
    |--------------------------------------------------------------------------
    */
    'multiple_ownership' => [
        'table_name' => 'ownerships',
        'roles' => [
            'owner' => [
                'display_name' => 'Owner',
                'permissions' => ['*'], // Wildcard means all permissions
            ],
            'editor' => [
                'display_name' => 'Editor',
                'permissions' => ['edit', 'view'],
            ],
            'viewer' => [
                'display_name' => 'Viewer',
                'permissions' => ['view'],
            ],
        ],
        'default_role' => 'viewer',
    ],
];
```

Usage
-----

[](#usage)

### Single Ownership Mode

[](#single-ownership-mode)

Basic Usage
-----------

[](#basic-usage)

### For Ownable Models (Models that can be owned)

[](#for-ownable-models-models-that-can-be-owned)

Add the `HasOwnership` trait to your model:

```
use Illuminate\Database\Eloquent\Model;
use Dibakar\Ownership\Traits\HasOwnership;

class Document extends Model
{
    use HasOwnership;
    // ...
}
```

### For Owner Models (Models that can own other models)

[](#for-owner-models-models-that-can-own-other-models)

Add the `IsOwner` trait to models that can own other models (like User, Team, etc.):

```
use Illuminate\Database\Eloquent\Model;
use Dibakar\Ownership\Traits\IsOwner;

class User extends Authenticatable
{
    use IsOwner;
    // ...
}
```

class Post extends Model { use HasOwnership;

```
// ...

```

}

```

#### Basic Operations

```php
// Creating a new post with the current user as owner
$post = Post::create([
    'title' => 'My First Post',
    'content' => 'This is my first post.'
]);

// Explicitly set the owner
$post->setOwner($user);

// Check ownership
if ($post->isOwnedBy($user)) {
    // User owns the post
}

// Get the owner
$owner = $post->owner;

// Transfer ownership
$post->transferOwnership($currentOwner, $newOwner);

// Clear the owner
$post->clearOwner();

```

### Multiple Ownership Mode

[](#multiple-ownership-mode)

First, update your config to use multiple ownership mode:

```
// config/ownership.php
return [
    'mode' => 'multiple',
    // ... rest of the config
];
```

Then add the `HasOwnership` trait to your model:

```
use Illuminate\Database\Eloquent\Model;
use Dibakar\Ownership\Traits\HasOwnership;

class Project extends Model
{
    use HasOwnership;

    // ...
}
```

#### Managing Multiple Owners

[](#managing-multiple-owners)

```
// Add an owner with a specific role
$project->addOwner($user, 'owner');

// Add multiple owners at once
$project->addOwners([$user1, $user2, $user3], 'editor', ['custom_permission']);

// Remove an owner
$project->removeOwner($user);

// Check if a user is an owner
if ($project->hasOwner($user)) {
    // User is an owner
}

// Get all owners with their roles
$owners = $project->getOwners();

// Get owners with a specific role
$editors = $project->getOwnersWithRole('editor');

// Check if a user has a specific role
if ($project->hasOwnerWithRole($user, 'admin')) {
    // User has admin role
}

// Update a user's role
$project->updateOwnerRole($user, 'admin');

// Sync owners (removes any owners not in the list)
$project->syncOwners([
    $user1,
    $user2,
    $user3,
], 'owner');

// Clear all owners
$project->clearAllOwners();
}

### Query Scopes

The package provides several query scopes to filter models by ownership:

```php
// Get all posts owned by the current user
$posts = Post::ownedByCurrent()->get();

// Get all posts owned by a specific user
$userPosts = Post::ownedBy($user)->get();

// In multiple ownership mode, get projects where user has a specific role
$projects = Project::whereHasOwnerWithRole($user, 'editor')->get();

// Get models where user has specific permission
$editablePosts = Post::whereUserHasPermission($user, 'edit')->get();
```

### Events

[](#events)

The package dispatches events when ownership changes occur:

```
use Dibakar\Ownership\Events\OwnershipCreated;
use Dibakar\Ownership\Events\OwnershipUpdated;
use Dibakar\Ownership\Events\OwnershipDeleted;
use Dibakar\Ownership\Events\OwnershipTransferred;

// Listen for ownership events
Event::listen(OwnershipCreated::class, function (OwnershipCreated $event) {
    $model = $event->model;
    $owner = $event->owner;
    $role = $event->role;

    // Handle the event
});
```

### Middleware

[](#middleware)

Protect your routes with the ownership middleware:

```
// routes/web.php
Route::middleware(['auth', 'ownership:post,edit'])
    ->group(function () {
        Route::get('/posts/{post}/edit', 'PostController@edit');
        Route::put('/posts/{post}', 'PostController@update');
    });

// With custom ownership check
Route::middleware(['auth', 'ownership:post,edit,App\Policies\CustomPostPolicy'])
    ->group(function () {
        // Your routes
    });
```

### Blade Directives

[](#blade-directives)

```
{{-- Check if current user owns the model --}}
@owned($post)
    Edit
@endowned

{{-- Check specific user ownership --}}
@owned($post, $specificUser)
    Owned by {{ $specificUser->name }}
@endowned

{{-- Check if user has specific permission --}}
@can('edit', $post)
    Edit
@endcan

@owned($model, $user = null)
    This content is only visible to the owner
@endowned

@canOwn($model, 'edit', $user = null)
    This content is only visible to users with edit permission
@endCanOwn

@isOwner($model, $user = null)
    This content is only visible to an owner
@endIsOwner
```

### Events

[](#events-1)

The package dispatches several events that you can listen to:

- `Dibakar\Ownership\Events\OwnershipCreated`
- `Dibakar\Ownership\Events\OwnershipUpdated`
- `Dibakar\Ownership\Events\OwnershipDeleted`
- `Dibakar\Ownership\Events\OwnershipTransferred`

Example listener:

```
namespace App\Listeners;

use Dibakar\Ownership\Events\OwnershipCreated;

class LogOwnershipCreated
{
    public function handle(OwnershipCreated $event)
    {
        // Handle the event
    }
}
```

Testing
-------

[](#testing)

Run the tests with:

```
composer test
```

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

License
-------

[](#license)

Example Usage
-------------

[](#example-usage)

### User Model

[](#user-model)

```
use Illuminate\Foundation\Auth\User as Authenticatable;
use Dibakar\Ownership\Traits\IsOwner;

class User extends Authenticatable
{
    use IsOwner;
    // ...
}
```

### Document Model

[](#document-model)

```
use Illuminate\Database\Eloquent\Model;
use Dibakar\Ownership\Traits\HasOwnership;

class Document extends Model
{
    use HasOwnership;
    // ...
}
```

### Controller Example

[](#controller-example)

```
class DocumentController extends Controller
{
    public function store(Request $request)
    {
        $document = Document::create($request->all());

        // Set the current user as the owner with admin role
        $document->addOwner(auth()->user(), 'admin');

        return response()->json($document, 201);
    }

    public function transfer(Document $document, User $newOwner)
    {
        $this->authorize('update', $document);

        // Transfer ownership
        $document->getOwner()->transferOwnershipTo($newOwner);

        return response()->json(['message' => 'Ownership transferred']);
    }
}
```

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Dibakar Mitra](https://github.com/dibakarmitra)
- [All Contributors](../../contributors)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance66

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~41 days

Total

2

Last Release

208d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/86a27be24348bc28aeefb406a99e47d6ee111f76a06b8f5e1371ae9745462bc9?d=identicon)[dibakar](/maintainers/dibakar)

---

Top Contributors

[![dibakarmitra](https://avatars.githubusercontent.com/u/8275598?v=4)](https://github.com/dibakarmitra "dibakarmitra (1 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (1 commits)")

---

Tags

laravellaravel-ownershipmulti-ownersownershipownership-managementsingle-ownerlaravelrolespermissionsownershipmulti-ownergatelaravel-ownershipsingle-ownerownership-management

### Embed Badge

![Health badge](/badges/dibakar-laravel-ownership/health.svg)

```
[![Health](https://phpackages.com/badges/dibakar-laravel-ownership/health.svg)](https://phpackages.com/packages/dibakar-laravel-ownership)
```

###  Alternatives

[spatie/laravel-permission

Permission handling for Laravel 12 and up

12.9k89.8M1.0k](/packages/spatie-laravel-permission)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[beatswitch/lock-laravel

A Laravel Driver for Lock.

15529.1k1](/packages/beatswitch-lock-laravel)[wnikk/laravel-access-rules

Simple system of ACR (access control rules) for Laravel, with roles, groups, unlimited inheritance and possibility of multiplayer use.

103.6k1](/packages/wnikk-laravel-access-rules)[erag/laravel-role-permission

A simple and easy-to-install role and permission management package for Laravel, supporting versions 10.x and 11.x

404.2k](/packages/erag-laravel-role-permission)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
