PHPackages                             cybercog/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. [Database &amp; ORM](/categories/database)
4. /
5. cybercog/laravel-ownership

ActiveLibrary[Database &amp; ORM](/categories/database)

cybercog/laravel-ownership
==========================

Laravel Ownership simplify management of Eloquent model's owner.

5.8.0(2mo ago)9126.6k↓48.2%16[1 issues](https://github.com/cybercog/laravel-ownership/issues)3MITPHPPHP ^8.0CI passing

Since Dec 17Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/cybercog/laravel-ownership)[ Packagist](https://packagist.org/packages/cybercog/laravel-ownership)[ Docs](https://komarev.com/sources/laravel-ownership)[ Fund](https://paypal.me/antonkomarev)[ RSS](/packages/cybercog-laravel-ownership/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (22)Used By (3)

[![cog-laravel-ownership](https://cloud.githubusercontent.com/assets/1849174/21737911/ee344682-d48e-11e6-9ace-eea37026ae6d.png)](https://cloud.githubusercontent.com/assets/1849174/21737911/ee344682-d48e-11e6-9ace-eea37026ae6d.png)

[![Discord](https://camo.githubusercontent.com/86e83e2f2ffe2f5caffed9d8886bb512bf42bf927dd8bb8e864d9e9983313ff7/68747470733a2f2f696d672e736869656c64732e696f2f7374617469632f76313f6c6f676f3d646973636f7264266c6162656c3d266d6573736167653d446973636f726426636f6c6f723d333633393366267374796c653d666c61742d737175617265)](https://discord.gg/dzbvW2utyF)[![Build](https://camo.githubusercontent.com/cbe8d670058643ad168cd0339055b7141155815daf0432a1bf0cf76537fad76c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6379626572636f672f6c61726176656c2d6f776e6572736869702f74657374732e796d6c3f7374796c653d666c61742d737175617265)](https://github.com/cybercog/laravel-ownership/actions/workflows/tests.yml)[![StyleCI](https://camo.githubusercontent.com/fb8da1f5ed567055d7f90f033da0858905c8edcdd3d7af61de4d15c7265239cc/68747470733a2f2f7374796c6563692e696f2f7265706f732f37363635313338362f736869656c64)](https://styleci.io/repos/76651386)[![Releases](https://camo.githubusercontent.com/820608ed6b4e7ba827d52e2db8623e7d83c7f095bce402a6327316c3bfa8dcc4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6379626572636f672f6c61726176656c2d6f776e6572736869702e7376673f7374796c653d666c61742d737175617265)](https://github.com/cybercog/laravel-ownership/releases)[![License](https://camo.githubusercontent.com/79c13f7c74e7fd9fd2536e7669e81b00c946b41fc51688fabdaf3db369a79760/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6379626572636f672f6c61726176656c2d6f776e6572736869702e7376673f7374796c653d666c61742d737175617265)](https://github.com/cybercog/laravel-ownership/blob/master/LICENSE)

Introduction
------------

[](#introduction)

Laravel Ownership simplify management of Eloquent model's owner. Group can be an owner of event, user can be an owner of chat room, organization can own licenses. It can be used for many cases not limited by authorship. Make any model as owner and create ownable models in a minutes!

Contents
--------

[](#contents)

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
    - [Prepare ownable model with strict ownership](#prepare-ownable-model-with-strict-ownership)
    - [Prepare ownable model with polymorphic ownership](#prepare-ownable-model-with-polymorphic-ownership)
    - [Available methods](#available-methods)
    - [Scopes](#scopes)
    - [Set authenticated user as owner automatically](#set-authenticated-user-as-owner-automatically)
- [Changelog](#changelog)
- [Upgrading](#upgrading)
- [Contributing](#contributing)
- [Testing](#testing)
- [Security](#security)
- [Credits](#credits)
- [Alternatives](#alternatives)
- [License](#license)
- [About CyberCog](#about-cybercog)

Features
--------

[](#features)

- Designed to work with Laravel Eloquent models
- Using contracts to keep high customization capabilities
- Each model can has owners of one type or use polymorphism
- Option to auto-assigning current authenticated user on model creation as owner
- Configurable auto-owner resolve strategy on model creation
- Option to manually assign owner on model creation
- Option to manually skip auto-assigning current user
- Transfer ownership (change owner)
- Make model orphaned (abandon owner)
- Various ownership checks and query scopes
- Following PHP Standard Recommendations:
    - [PSR-2 (Coding Style Guide)](http://www.php-fig.org/psr/psr-2/).
    - [PSR-4 (Autoloading Standard)](http://www.php-fig.org/psr/psr-4/).
- Covered with unit tests

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

[](#installation)

First, pull in the package through Composer.

```
composer require cybercog/laravel-ownership
```

#### Register Package Manually (optional)

[](#register-package-manually-optional)

If you disabled package auto-discovery you can register it manually.

Include the service provider within `app/config/app.php`.

```
'providers' => [
    Cog\Laravel\Ownership\Providers\OwnershipServiceProvider::class,
];
```

Usage
-----

[](#usage)

Laravel Ownership allows model to have strict owner model type (`HasOwner` trait) or use polymorphic relation (`HasMorphOwner` trait).

Strict ownership is useful when model can belong to only one model type. Attempt to set owner of not defined model type will throw an exception `InvalidOwnerType`. *Example: Only users allowed to create posts.*

Polymorphic ownership is useful when model can belong to owners of different types. *Example: Users and Organizations can upload applications to marketplace.*

### Prepare owner model

[](#prepare-owner-model)

At the owner model use `CanBeOwner` contract and implement it:

```
use Cog\Contracts\Ownership\CanBeOwner as CanBeOwnerInterface;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements CanBeOwnerInterface
{
    // ...
}
```

### Prepare ownable model with strict ownership

[](#prepare-ownable-model-with-strict-ownership)

Use `Ownable` contract in model which will get ownership behavior and implement it or just use `HasOwner` trait.

```
use Cog\Contracts\Ownership\Ownable as OwnableInterface;
use Cog\Laravel\Ownership\Traits\HasOwner;
use Illuminate\Database\Eloquent\Model;

class Article extends Model implements OwnableInterface
{
    use HasOwner;
}
```

Ownable model with strict ownership must have in database additional nullable column to store owner relation:

```
Schema::table('articles', function (Blueprint $table) {
    $table->integer('owned_by_id')->unsigned()->nullable();

    $table->index('owned_by_id');
});
```

#### Overwrite strict ownership owner's foreign key

[](#overwrite-strict-ownership-owners-foreign-key)

By default, owner model will be the same as `config('auth.providers.users.model')` provides.

To override default owner model in strict ownership, it's primary key or foreign key extend your ownable model with additional attributes:

```
use Cog\Contracts\Ownership\Ownable as OwnableInterface;
use Cog\Laravel\Ownership\Traits\HasOwner;
use Illuminate\Database\Eloquent\Model;

class Article extends Model implements OwnableInterface
{
    use HasOwner;

    protected $ownerModel = Group::class;
    protected $ownerPrimaryKey = 'gid';
    protected $ownerForeignKey = 'group_id';
}
```

### Prepare ownable model with polymorphic ownership

[](#prepare-ownable-model-with-polymorphic-ownership)

Use `Ownable` contract in model which will get polymorphic ownership behavior and implement it or just use `HasMorphOwner` trait.

```
use Cog\Contracts\Ownership\Ownable as OwnableInterface;
use Cog\Laravel\Ownership\Traits\HasMorphOwner;
use Illuminate\Database\Eloquent\Model;

class Article extends Model implements OwnableInterface
{
    use HasMorphOwner;
}
```

Ownable model with polymorphic ownership must have in database additional nullable columns to store owner relation:

```
Schema::table('articles', function (Blueprint $table) {
    $table->nullableMorphs('owned_by');
});
```

### Available methods

[](#available-methods)

#### Get owner relation

[](#get-owner-relation)

```
$article->ownedBy();
$article->owner();
```

#### Get model owner

[](#get-model-owner)

```
$article->getOwner();
$article->ownedBy;
$article->owner;
```

#### Change (set) owner

[](#change-set-owner)

```
$article->changeOwnerTo($owner);
```

#### Abandon (unset) owner

[](#abandon-unset-owner)

```
$article->abandonOwner();
```

#### Check if has owner

[](#check-if-has-owner)

```
$article->hasOwner();
```

#### Check if owned by owner

[](#check-if-owned-by-owner)

```
$article->isOwnedBy($owner);
```

#### Check not owned by owner

[](#check-not-owned-by-owner)

```
$article->isNotOwnedBy($owner);
```

#### Manually define default owner on model creation

[](#manually-define-default-owner-on-model-creation)

```
$article = new Article;
$article->withDefaultOwner()->save();
```

*Will use `resolveDefaultOwner()` method under the hood.*

Or provide concrete owner:

```
$user = User::where('name', 'admin')->first();
$article = new Article;
$article->withDefaultOwner($user)->save();
```

#### Skip defining default owner on model creation

[](#skip-defining-default-owner-on-model-creation)

```
$article = new Article;
$article->withoutDefaultOwner()->save();
```

### Scopes

[](#scopes)

#### Scope models by owner

[](#scope-models-by-owner)

```
Article::whereOwnedBy($owner)->get();
```

#### Scope models by not owned by owner

[](#scope-models-by-not-owned-by-owner)

```
Article::whereNotOwnedBy($owner)->get();
```

### Set authenticated user as owner automatically

[](#set-authenticated-user-as-owner-automatically)

To set currently authenticated user as owner for ownable model create - extend it with attribute `withDefaultOwnerOnCreate`. It works for both strict and polymorphic ownership behavior.

```
use Cog\Contracts\Ownership\Ownable as OwnableInterface;
use Cog\Laravel\Ownership\Traits\HasOwner;
use Illuminate\Database\Eloquent\Model;

class Article extends Model implements OwnableInterface
{
    use HasOwner;

    protected $withDefaultOwnerOnCreate = true;
}
```

To override strategy of getting default owner extend ownable model with `resolveDefaultOwner` method:

```
use Cog\Contracts\Ownership\Ownable as OwnableInterface;
use Cog\Laravel\Ownership\Traits\HasOwner;
use Illuminate\Database\Eloquent\Model;

class Article extends Model implements OwnableInterface
{
    use HasOwner;

    public $withDefaultOwnerOnCreate = true;

    /**
     * Resolve entity default owner.
     *
     * @return \Cog\Contracts\Ownership\CanBeOwner|null
     */
    public function resolveDefaultOwner()
    {
        return \App\User::where('name', 'admin')->first();
    }
}
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Upgrading
---------

[](#upgrading)

Please see [UPGRADING](UPGRADING.md) for detailed upgrade instructions.

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

[](#contributing)

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

Testing
-------

[](#testing)

Run the tests with:

```
vendor/bin/phpunit
```

Security
--------

[](#security)

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

Credits
-------

[](#credits)

[![@antonkomarev](https://avatars.githubusercontent.com/u/1849174?s=110)
Anton Komarev](https://github.com/antonkomarev)[![@soap](https://avatars.githubusercontent.com/u/1073690?s=110)
Prasit Gebsaap](https://github.com/soap)[Laravel Ownership contributors list](../../contributors)

Alternatives
------------

[](#alternatives)

*Feel free to add more alternatives as Pull Request.*

License
-------

[](#license)

- `Laravel Ownership` package is open-sourced software licensed under the [MIT license](LICENSE) by [Anton Komarev](https://komarev.com).
- `Intellectual Property` image licensed under [Creative Commons 3.0](https://creativecommons.org/licenses/by/3.0/us/) by Arthur Shlain.
- `Fat Boss` image licensed under [Creative Commons 3.0](https://creativecommons.org/licenses/by/3.0/us/) by Gan Khoon Lay.

About CyberCog
--------------

[](#about-cybercog)

[CyberCog](https://cybercog.su) is a Social Unity of enthusiasts. Research the best solutions in product &amp; software development is our passion.

- [Follow us on Twitter](https://twitter.com/cybercog)
- [Read our articles on Medium](https://medium.com/cybercog)

[![CyberCog](https://cloud.githubusercontent.com/assets/1849174/18418932/e9edb390-7860-11e6-8a43-aa3fad524664.png)](https://cybercog.su)

###  Health Score

61

—

FairBetter than 99% of packages

Maintenance85

Actively maintained with recent releases

Popularity44

Moderate usage in the ecosystem

Community23

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 92.9% 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 ~197 days

Recently: every ~275 days

Total

18

Last Release

79d ago

Major Versions

1.0.1 → 2.0.02016-12-17

2.2.0 → 3.0.02017-04-10

3.1.0 → 4.0.02017-09-09

4.0.0 → 5.0.02017-09-12

PHP version history (3 changes)1.0.0PHP ^5.6|^7.0

5.3.0PHP ^7.1.3|^8.0

5.4.0PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/b3fddc40462126bbc119e373ed6a3f942a90a400f30c076c447c0625b841c4ef?d=identicon)[antonkomarev](/maintainers/antonkomarev)

---

Top Contributors

[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (65 commits)")[![dionysiosarvanitis](https://avatars.githubusercontent.com/u/1359269?v=4)](https://github.com/dionysiosarvanitis "dionysiosarvanitis (1 commits)")[![JoshuaDoshua](https://avatars.githubusercontent.com/u/1930699?v=4)](https://github.com/JoshuaDoshua "JoshuaDoshua (1 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")[![soap](https://avatars.githubusercontent.com/u/1073690?v=4)](https://github.com/soap "soap (1 commits)")[![WilburJZHAO](https://avatars.githubusercontent.com/u/56952171?v=4)](https://github.com/WilburJZHAO "WilburJZHAO (1 commits)")

---

Tags

authorcogcreatoreloquentlaravelownableownable-modelsownedownerownershippackagepolymorphicpolymorphismproprietortraitlaraveleloquenttraitcreatordomainownableownershipcogmorphmakercybercogpolymorphicmasterauthorcopyrightownerproprietorowned

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[cybercog/laravel-ban

Laravel Ban simplify blocking and banning Eloquent models.

1.1k651.8k11](/packages/cybercog-laravel-ban)[cybercog/laravel-love

Make Laravel Eloquent models reactable with any type of emotions in a minutes!

1.2k302.7k1](/packages/cybercog-laravel-love)[cviebrock/eloquent-taggable

Easy ability to tag your Eloquent models in Laravel.

567694.8k3](/packages/cviebrock-eloquent-taggable)[rtconner/laravel-likeable

Trait for Laravel Eloquent models to allow easy implementation of a 'like' or 'favorite' or 'remember' feature.

394388.0k5](/packages/rtconner-laravel-likeable)[reedware/laravel-relation-joins

Adds the ability to join on a relationship by name.

2121.2M13](/packages/reedware-laravel-relation-joins)[cybercog/laravel-eloquent-flag

Laravel Eloquent boolean &amp; timestamp flagged attributes behavior.

13518.7k](/packages/cybercog-laravel-eloquent-flag)

PHPackages © 2026

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