Get expert guidance in a few days with a Laravel code review

Handle ownership relationships between Eloquent models with Laravel Ownable

Last updated on by

Handle ownership relationships between Eloquent models with Laravel Ownable image

The Laravel Ownable package, created by Abdullah Sowailem, provides a flexible and straightforward way to manage ownership of any model by another model in your Laravel application.

Key Features

  • Flexible Ownership: Any model can own any other model
  • Ownership Transfer: Transfer ownership between different owners
  • Ownership History: Keep track of ownership changes over time
  • Current Owner: Easily retrieve the current owner of any ownable item
  • Bulk Operations: Check ownership status and manage multiple ownables
  • Automatic Cleanup: Automatically clean up ownership records when models are deleted
  • Facade Support: Use the convenient Owner facade for ownership operations

Example Usage

Let's say we have User and Task models. With the Laravel Ownable package, we can represent ownership by using the Owner and Ownable contracts along with the HasOwnables and isOwnable traits in our respective models.

use Sowailem\Ownable\Traits\HasOwnables;
use Sowailem\Ownable\Contracts\Owner as OwnerContract;
 
// Owner model (e.g., User)
class User extends Authenticatable implements OwnerContract
{
use HasOwnables;
}
use Sowailem\Ownable\Traits\IsOwnable;
use Sowailem\Ownable\Contracts\Ownable as OwnableContract;
 
// Ownable Model
class Task extends Model implements OwnableContract
{
use IsOwnable;
}

With that now in place, you have several methods available on your models to give, take, remove, and check ownership.

$user = User::first();
$task = Task::first();
 
// Give a user ownership of a task
$user->giveOwnershipTo($task);
 
$task->ownedBy($user);
 
if ($task->isOwnedBy($user)) {
// Check if the user owns the task
}
 
// Transfer ownership to another user
$someOtherUser = User::find(2);
$user->transferOwnership($task, $someOtherUser);
 
// Get the current owner of an item
$currentOwner = $task->currentOwner();
 
// Get all owners (including historical ownership)
$allOwnersOfTheTask = $task->owners()->get();
 
// Remove Ownership
$user->takeOwnershipFrom($task);

If you prefer to use the Facade implementation, it is also available.

use Illuminate\Support\Facades\Log;
use Sowailem\Ownable\Facades\Owner;
 
$user = User::find(4);
$task = Task::find(2);
 
Owner::give($user, $task);
 
if (Owner::check($user, $task)) {
Log::info("User {$user->id} is the owner of task {$task->id}");
}
 
$newOwner = User::find(1);
 
Owner::transfer($user, $newOwner, $task);
Log::info("Task {$task->id} is now owned by {$task->currentOwner()->name}");

Another nice feature of this package is that it includes a migration that helps keep track of changes in the ownership of your Models. The entries in your database look similar to this:

Learn more about this package and view the source code on GitHub.

Yannick Lyn Fatt photo

Staff Writer at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Generate Complete Application Modules with a Single Command using Laravel TurboMaker image

Generate Complete Application Modules with a Single Command using Laravel TurboMaker

Read article
`hasSole()` Collection Method in Laravel 12.49.0 image

`hasSole()` Collection Method in Laravel 12.49.0

Read article
Install Laravel Package Guidelines and Skills in Boost image

Install Laravel Package Guidelines and Skills in Boost

Read article
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article