This package allows you to group your user models, you can use this for various things.
First, install the package via composer.
composer require ohkannaduh/groups
If you are using Laravel version 5.5 or lower you'll need to register OhKannaDuh\Groups\GroupsServiceProvider
in your config/app.php
providers array.
'providers' => [
...
/*
* Package Service Providers...
*/
OhKannaDuh\Groups\GroupsServiceProvider::class
...
],
To publish config files and migrations run:
php artisan vendor:publish --provider="OhKannaDuh\Groups\GroupsServiceProvider"
Configure the package by modifying config/groups.php
Then finally run the migrations:
php artisan migrate
...
use OhKannaDuh\Groups\Traits\Groupable;
use OhKannaDuh\Groups\Contracts\GroupableContract;
...
class User extends Model implements GroupableContract
{
use Groupable;
...
}
$group->addUser($user);
$group->addUsers($users);
$group->removeUser($user);
$group->removeUsers($users);
$group->contains($user)
$group->users;
$user->groups;
$group->messages;
$message->user;
$message->group
You can add this method to your user class to add custom logic for adding users to groups:
public function canAddToGroup(\OhKannaDuh\Groups\Model\Group $group): bool
Here is an example:
public function canAddToGroup(\OhKannaDuh\Groups\Model\Group $group): bool
{
foreach ($group->users as $user) {
/**
* This user has been blocked or has blocked the other user.
* Don't add them to the group.
*/
if ($user->isBlocked($this) === true) {
return false;
}
}
return true;
}
This method just returns true
by default.
A similar thing can be done to determine if a user can leave a group:
public function canRemoveFromGroup(\OhKannaDuh\Groups\Model\Group $group): bool
Here is an example:
public function canRemoveFromGroup(\OhKannaDuh\Groups\Model\Group $group): bool
{
# Don't remove the user if they are the last remaining group member
return count($group) > 1;
}
This method just returns true
by default.
A similar thing can be done to determine if a user can send a message to a group:
public function canSendMessageToGroup(\OhKannaDuh\Groups\Model\Group $group): bool
Here is an example:
public function canSendMessageToGroup(\OhKannaDuh\Groups\Model\Group $group): bool
{
# Only users that are admins can send messages to groups
return $this->isAdmin();
}
This method just returns true
by default.