PHPackages                             sowailem/ownable - 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. sowailem/ownable

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

sowailem/ownable
================

A Laravel package to handle ownership relationships between models

2.0.9(4mo ago)731.2k↓83.3%6MITPHPPHP ^8.3CI passing

Since Aug 10Pushed 4mo ago3 watchersCompare

[ Source](https://github.com/sowailem/Ownable)[ Packagist](https://packagist.org/packages/sowailem/ownable)[ RSS](/packages/sowailem-ownable/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (2)Dependencies (6)Versions (19)Used By (0)

Laravel Ownable Package
=======================

[](#laravel-ownable-package)

A powerful, automated, and API-driven Laravel package to handle ownership relationships between Eloquent models. This package provides a seamless way to manage ownership, track history, and automatically attach ownership data to your API responses without needing to modify your models with traits or interfaces.

Key Features
------------

[](#key-features)

- **Hands-off Integration**: No traits or interfaces required on your models.
- **Automatic API Attachment**: Automatically inject ownership information into your JSON responses via middleware.
- **Dynamic Registration**: Register "ownable" models through configuration or a dedicated REST API.
- **Centralized Management**: Manage all ownership operations via the `Owner` facade or service.
- **Ownership History**: Keep track of ownership changes over time.
- **Built-in API Endpoints**: Ready-to-use routes for managing ownership and ownable model registrations.
- **Blade Directive**: Simple `@owns` directive for UI-based authorization checks.

Requirements
------------

[](#requirements)

- PHP ^8.3
- Laravel ^12.0

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

[](#installation)

1. Require the package via Composer:

```
composer require sowailem/ownable
```

2. Run the migrations:

```
php artisan migrate
```

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

[](#configuration)

The `config/ownable.php` file allows you to customize:

- `owner_model`: The default model class that acts as an owner (e.g., `App\Models\User`).
- `ownable_models`: An array of model classes that can be owned (static registration).
- `routes`: Custom prefix and middleware for the built-in API.
- `automatic_attachment`: Enable/disable automatic ownership injection and customize the response key.

Usage Guide
-----------

[](#usage-guide)

### 1. Basic Operations

[](#1-basic-operations)

The `Owner` facade is your primary tool for managing ownership relationships.

#### Giving Ownership

[](#giving-ownership)

Assign ownership of any model to another. This automatically handles marking previous ownerships for that entity as inactive.

```
use Sowailem\Ownable\Facades\Owner;

// A User owning a Post
Owner::give($user, $post);

// A Team owning a Project
Owner::give($team, $project);
```

#### Checking Ownership

[](#checking-ownership)

Quickly verify if a specific owner currently owns an entity.

```
if (Owner::check($user, $post)) {
    // Authorized
}
```

#### Transferring Ownership

[](#transferring-ownership)

Transfer ownership from one entity to another.

```
Owner::transfer($oldOwner, $newOwner, $post);
```

#### Retrieving Current Owner

[](#retrieving-current-owner)

Get the actual model instance of the current owner.

```
$owner = Owner::currentOwner($post); // Returns User instance, Team instance, etc.
```

#### Removing Ownership

[](#removing-ownership)

Clear the current ownership without necessarily assigning a new one.

```
Owner::remove($post);
```

### 2. Automatic API Attachment

[](#2-automatic-api-attachment)

This is the most powerful feature of the package. The `AttachOwnershipMiddleware` is automatically registered globally. It recursively scans your JSON responses (from Controllers or API Resources) and injects ownership data for any model registered as "ownable".

#### How it works:

[](#how-it-works)

1. It looks for Eloquent models in your `JsonResponse`.
2. It checks if the model class is registered in `config/ownable.php` or via the dynamic API.
3. If matched, it fetches the current owner and appends it to the JSON object.

#### Registration:

[](#registration)

Add models to `config/ownable.php`:

```
'ownable_models' => [
    \App\Models\Post::class,
    \App\Models\Comment::class,
],
```

#### JSON Response Example:

[](#json-response-example)

Before:

```
{
    "id": 1,
    "title": "Hello World"
}
```

After (Automatic):

```
{
    "id": 1,
    "title": "Hello World",
    "ownership": {
        "id": 45,
        "owner_id": 1,
        "owner_type": "User",
        "ownable_id": 1,
        "ownable_type": "Post",
        "is_current": true,
        "owner": {
            "id": 1,
            "name": "John Doe"
        }
    }
}
```

#### Customization:

[](#customization)

You can change the injection key and toggle the feature in `config/ownable.php`:

```
'automatic_attachment' => [
    'enabled' => true,
    'key' => 'meta_ownership', // Change "ownership" to something else
],
```

### 3. Practical Examples

[](#3-practical-examples)

#### Scenario A: Multi-Level Ownership

[](#scenario-a-multi-level-ownership)

You might have `Users` owning `Projects`, and `Projects` owning `Tasks`.

```
// User owns Project
Owner::give($user, $project);

// Project owns Task
Owner::give($project, $task);

// Check if project owns task
Owner::check($project, $task); // true
```

#### Scenario B: Middleware-based Authorization

[](#scenario-b-middleware-based-authorization)

Create a custom middleware to protect routes based on ownership:

```
public function handle($request, $next)
{
    $post = $request->route('post');

    if (!Owner::check($request->user(), $post)) {
        abort(403);
    }

    return $next($request);
}
```

#### Scenario C: Dynamic Registration Workflow

[](#scenario-c-dynamic-registration-workflow)

Register models as "ownable" on the fly without changing code:

```
curl -X POST http://your-app.test/api/ownable/ownable-models \
     -H "Content-Type: application/json" \
     -d '{"name": "Document", "model_class": "App\\Models\\Document", "description": "Client documents"}'
```

Now, all `Document` models returned in APIs will automatically include ownership data.

### 3. Blade Directive

[](#3-blade-directive)

Check ownership directly in your Blade views:

```
@owns($user, $post)
    Edit Post
@else
    Read Only
@endowns
```

API Reference
-------------

[](#api-reference)

The package provides several endpoints for managing ownership (prefixed by `api/ownable` by default):

### Ownership Records

[](#ownership-records)

- `GET /api/ownable/ownerships`: List and filter ownership history.
- `POST /api/ownable/ownerships/give`: Give ownership of an ownable entity to an owner.
- `POST /api/ownable/ownerships/transfer`: Transfer ownership from one owner to another.
- `POST /api/ownable/ownerships/check`: Check if an owner owns a specific entity.
- `POST /api/ownable/ownerships/remove`: Remove ownership of an entity.
- `POST /api/ownable/ownerships/current`: Get the current owner of an entity.

### Ownable Models (Dynamic Registration)

[](#ownable-models-dynamic-registration)

- `GET /api/ownable/ownable-models`: List models registered for automatic attachment.
- `POST /api/ownable/ownable-models`: Register a new model class as "ownable".
- `GET|PUT|DELETE /api/ownable/ownable-models/{id}`: Manage specific ownable model registrations.

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

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

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance75

Regular maintenance activity

Popularity31

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 94.2% 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 ~12 days

Recently: every ~0 days

Total

17

Last Release

136d ago

Major Versions

1.0.6 → 2.0.02026-02-15

PHP version history (2 changes)1.0.0PHP ^8.0

2.0.0PHP ^8.3

### Community

Maintainers

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

---

Top Contributors

[![sowailem](https://avatars.githubusercontent.com/u/6251878?v=4)](https://github.com/sowailem "sowailem (65 commits)")[![ylynfatt](https://avatars.githubusercontent.com/u/19831?v=4)](https://github.com/ylynfatt "ylynfatt (2 commits)")[![ChrisThompsonTLDR](https://avatars.githubusercontent.com/u/348801?v=4)](https://github.com/ChrisThompsonTLDR "ChrisThompsonTLDR (1 commits)")[![hdaklue](https://avatars.githubusercontent.com/u/107682410?v=4)](https://github.com/hdaklue "hdaklue (1 commits)")

---

Tags

laravellaravel-packageownable-modelsphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sowailem-ownable/health.svg)

```
[![Health](https://phpackages.com/badges/sowailem-ownable/health.svg)](https://phpackages.com/packages/sowailem-ownable)
```

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k54.9M11.6k](/packages/illuminate-database)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[laravel/horizon

Dashboard and code-driven configuration for Laravel queues.

4.2k95.4M306](/packages/laravel-horizon)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M193](/packages/laravel-ai)[moonshine/moonshine

Laravel administration panel

1.3k253.1k81](/packages/moonshine-moonshine)[tallstackui/tallstackui

TallStackUI is a powerful suite of Blade components that elevate your workflow of Livewire applications.

725173.0k14](/packages/tallstackui-tallstackui)

PHPackages © 2026

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