1. Go to this page and download the library: Download naviisml/laravel-ownables library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
naviisml / laravel-ownables example snippets
use Naviisml\Ownable\Traits\HasOwnables;
use Naviisml\Ownable\Traits\IsOwnable;
use Naviisml\Ownable\Contracts\Ownable as OwnableContract;
use Naviisml\Ownable\Contracts\Owner as OwnerContract;
// Owner model (e.g., User)
class User extends Authenticatable implements OwnerContract
{
use HasOwnables;
}
// Another Owner model (e.g., Company)
class Company extends Model implements OwnerContract
{
use HasOwnables;
}
// Ownable model
class Post extends Model implements OwnableContract
{
use IsOwnable;
// Optional: restrict which models can own this model
// If omitted or left empty, any model can be an owner
protected array $allowedOwners = [
User::class,
Company::class,
];
}
$user = User::first();
$post = Post::first();
// Give ownership
$user->giveOwnershipTo($post);
// Or
$post->ownedBy($user);
// Or using facade
Owner::give($user, $post);
// Check ownership
if ($user->owns($post)) {
// User owns this post
}
// Or
if ($post->isOwnedBy($user)) {
// Post is owned by this user
}
// Or using facade
if (Owner::check($user, $post)) {
// Check ownership using facade
}
// Transfer ownership
$newOwner = User::find(2);
$user->transferOwnership($post, $newOwner);
// Or
$post->transferOwnershipTo($newOwner);
// Or using facade
Owner::transfer($user, $newOwner, $post);
// Get all owned items
$user->ownables()->get();
// Get current owner of an item
$currentOwner = $post->currentOwner();
// Get all owners (including historical)
$allOwners = $post->owners()->get();
// Get only current owners
$currentOwners = $post->owners()->wherePivot('is_current', true)->get();