Eloquent Shareables is a lightweight Laravel package that allows you to easily share Eloquent models with different audiences and owners. It supports assigning specific access levels, managing unique sharing tokens, and querying shared models.
You can install the package via Composer:
composer require whilesmart/eloquent-shareablesYou should publish and run the migrations:
php artisan vendor:publish --tag="shareables-migrations"
php artisan migrateYou can optionally publish the config file:
php artisan vendor:publish --tag="shareables-config"This will create a config/sharables.php file in your application directory.
Add the Shareable trait to any Eloquent model you want to share:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Whilesmart\Shareables\Traits\Shareable;
class Post extends Model
{
use Shareable;
}To share a model, call the share() method:
// Share a post with read-only access to a specific audience, owned by the current user
$share = $post->share('read', $user, 'team_123');
// Share a post publicly with a custom or automatically generated token
$publicShare = $post->share('view', $user);
// A unique token (e.g. Str::random(40)) is generated if none is passed.You can check if a model is currently shared with an audience or via a specific token:
// Check if shared with an audience (e.g. team_123)
if ($post->isSharedWith('team_123')) {
// Shared!
}
// Check if shared via a specific access token
if ($post->isSharedViaToken($token)) {
// Shared!
}Shares can be revoked either individually (for an audience) or all at once:
// Revoke sharing for a specific audience
$post->revokeShare('team_123');
// Revoke all shares for this model
$post->revokeAllShares();Use the sharedWith query scope to retrieve models shared with a specific audience:
$posts = Post::sharedWith('team_123')->get();You can run the package test suite using:
composer testPlease see CHANGELOG for more information on what has changed recently.
The MIT License (MIT). Please see License File for more information.