Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

User to Team associations with invitation system for the Laravel Framework

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.md
NotificationsYou must be signed in to change notification settings

oliuz/teamwork

Repository files navigation

Latest VersionSoftware LicenseBuild Statuscodecov.ioSensioLabsInsightScrutinizer Code Quality

Teamwork is the fastest and easiest method to add a User / Team association with Invites to yourLaravel project.

Contents

For Laravel ^8.0|^9.0

"oliuz/teamwork": "^9.0"

Add the version you need to your composer.json. Then runcomposer install orcomposer update.

(or runcomposer require oliuz/teamwork if you prefere that)

TheTeamwork Facade will be installed automatically within the Service Provider.

To publish Teamwork's configuration and migration files, run thevendor:publish command.

php artisan vendor:publish --provider="Mpociot\Teamwork\TeamworkServiceProvider"

This will create ateamwork.php in your config directory.The default configuration should work just fine for you, but you can take a look at it, if you want to customize the table / model names Teamwork will use.

Run themigration command, to generate all tables needed for Teamwork.If your users are stored in a different table other thanusers be sure to modify the published migration.

php artisan migrate

After the migration, 3 new tables will be created:

  • teams — stores team records
  • team_user — storesmany-to-many relations between users and teams
  • team_invites — stores pending invites for email addresses to teams

You will also notice that a new columncurrent_team_id has been added to your users table.This column will define the Team, the user is currently assigned to.

Add theUserHasTeams trait to your existing User model:

<?phpnamespaceApp;useMpociot\Teamwork\Traits\UserHasTeams;class Userextends Model {use UserHasTeams;// Add this trait to your model}

This will enable the relation withTeam and add the following methodsteams(),ownedTeams()currentTeam(),invites(),isTeamOwner(),isOwnerOfTeam($team),attachTeam($team, $pivotData = []),detachTeam($team),attachTeams($teams),detachTeams($teams),switchTeam($team),isOwnerAuth(),isOwnerAuthCheck() within yourUser model.

Don't forget to dump composer autoload

composer dump-autoload

If you would like to use the middleware to protect to current team owner then just add the middleware provider to yourapp\Http\Kernel.php file.

protected$routeMiddleware = [        ...'teamowner' => \Mpociot\Teamwork\Middleware\TeamOwner::class,        ...    ];

Afterwards you can use theteamowner middleware in your routes file like so.

Route::get('/owner',function(){return"Owner of current team.";})->middleware('auth','teamowner');

Now only if the authenticated user is the owner of the current team can access that route.

This middleware is aimed to protect routes where only the owner of the team can edit/create/delete that model

And you are ready to go.

The easiest way to give your new Laravel project Team abilities is by using themake:teamwork command.

php artisan make:teamwork

This command will create all views, routes, model and controllers to make your new project team-ready.

Out of the box, the following parts will be created for you:

  • Team listing
  • Team creation / editing / deletion
  • Invite new members to teams
  • Team model

Imagine it as a themake:auth command for Teamwork.

To get started, take a look at the new installed/teams route in your project.

Let's start by creating two different Teams.

$team=newTeam();$team->owner_id = User::where('username','=','sebastian')->first()->getKey();$team->name ='My awesome team';$team->save();$myOtherCompany =newTeam();$myOtherCompany->owner_id = User::where('username','=','marcel')->first()->getKey();$myOtherCompany->name ='My other awesome team';$myOtherCompany->save();

Now thanks to theUserHasTeams trait, assigning the Teams to the user is uber easy:

$user = User::where('username','=','sebastian')->first();// team attach alias$user->attachTeam($team,$pivotData);// First parameter can be a Team object, array, or id// or eloquent's original technique$user->teams()->attach($team->id);// id only

By using theattachTeam method, if the User has no Teams assigned, thecurrent_team_id column will automatically be set.

The currently assigned Team of a user can be accessed through thecurrentTeam relation like this:

echo"I'm currently in team:" . Auth::user()->currentTeam->name;echo"The team owner is:" . Auth::user()->currentTeam->owner->username;echo"I also have these teams:";print_r( Auth::user()->teams );echo"I am the owner of these teams:";print_r( Auth::user()->ownedTeams );echo"My team has" . Auth::user()->currentTeam->users->count() ." users.";

TheTeam model has access to these methods:

  • invites() — Returns a many-to-many relation to associated invitations.
  • users() — Returns a many-to-many relation with all users associated to this team.
  • owner() — Returns a one-to-one relation with the User model that owns this team.
  • hasUser(User $user) — Helper function to determine if a user is a teammember

If you need to check if the User is a team owner (regardless of the current team) use theisTeamOwner() method on the User model.

if( Auth::user()->isTeamOwner() ){echo"I'm a team owner. Please let me pay more.";}

Additionally if you need to check if the user is the owner of a specific team, use:

$team = Auth::user()->currentTeam;if( Auth::user()->isOwnerOfTeam($team ) ){echo"I'm a specific team owner. Please let me pay even more.";}

TheisOwnerOfTeam method also allows an array or id as team parameter.

If your Users are members of multiple teams you might want to give them access to aswitch team mechanic in some way.

This means that the user has one "active" team, that is currently assigned to the user. All other teams still remain attached to the relation!

Glad we have theUserHasTeams trait.

try {Auth::user()->switchTeam($team_id );// Or remove a team association at allAuth::user()->switchTeam(null );}catch(UserNotInTeamException$e ){// Given team is not allowed for the user}

Just like theisOwnerOfTeam method,switchTeam accepts a Team object, array, id or null as a parameter.

The best team is of no avail if you're the only team member.

To invite other users to your teams, use theTeamwork facade.

Teamwork::inviteToTeam($email,$team,function($invite ){// Send email to user / let them know that they got invited});

You can also send invites by providing an object with anemail property like:

$user = Auth::user();Teamwork::inviteToTeam($user ,$team,function($invite ){// Send email to user / let them know that they got invited});

This method will create aTeamInvite model and return it in the callable third parameter.

This model has these attributes:

  • email — The email that was invited.
  • accept_token — Unique token used to accept the invite.
  • deny_token — Unique token used to deny the invite.

In addition to these attributes, the model has these relations:

  • user() — one-to-one relation using theemail as a unique identifier on the User model.
  • team() — one-to-one relation return the Team, that invite was aiming for.
  • inviter() — one-to-one relation return the User, that created the invite.

Note:TheinviteToTeam method willnot check if the given email already has a pending invite. To check for pending invites use thehasPendingInvite method on theTeamwork facade.

Example usage:

if( !Teamwork::hasPendingInvite($request->email,$request->team) ){Teamwork::inviteToTeam($request->email,$request->team,function($invite ){// Send email to user});}else {// Return error - user already invited}

Once you invited other users to join your team, in order to accept the invitation use theTeamwork facade once again.

$invite = Teamwork::getInviteFromAcceptToken($request->token );// Returns a TeamworkInvite model or nullif($invite )// valid token found{Teamwork::acceptInvite($invite );}

TheacceptInvite method does two thing:

  • CallattachTeam with the invite-team on the currently authenticated user.
  • Delete the invitation afterwards.

Just like accepting invites:

$invite = Teamwork::getInviteFromDenyToken($request->token );// Returns a TeamworkInvite model or nullif($invite )// valid token found{Teamwork::denyInvite($invite );}

ThedenyInvite method is only responsible for deleting the invitation from the database.

If you need to run additional processes after attaching/detaching a team from a user or inviting a user, you can Listen for these events:

\Mpociot\Teamwork\Events\UserJoinedTeam\Mpociot\Teamwork\Events\UserLeftTeam\Mpociot\Teamwork\Events\UserInvitedToTeam

In yourEventServiceProvider add your listener(s):

/** * The event listener mappings for the application. * * @var array */protected$listen = [    ...    \Mpociot\Teamwork\Events\UserJoinedTeam::class => [App\Listeners\YourJoinedTeamListener::class,    ],    \Mpociot\Teamwork\Events\UserLeftTeam::class => [App\Listeners\YourLeftTeamListener::class,    ],    \Mpociot\Teamwork\Events\UserInvitedToTeam::class => [App\Listeners\YourUserInvitedToTeamListener::class,    ],];

The UserJoinedTeam and UserLeftTeam event exposes the User and Team's ID. In your listener, you can access them like so:

<?phpnamespaceApp\Listeners;useMpociot\Teamwork\Events\UserJoinedTeam;class YourJoinedTeamListener{/**     * Create the event listener.     *     * @return void     */publicfunction__construct()    {//    }/**     * Handle the event.     *     * @param  UserJoinedTeam  $event     * @return void     */publicfunctionhandle(UserJoinedTeam$event)    {// $user = $event->getUser();// $teamId = $event->getTeamId();// Do something with the user and team ID.    }}

The UserInvitedToTeam event contains an invite object which could be accessed like this:

<?phpnamespaceApp\Listeners;useMpociot\Teamwork\Events\UserInvitedToTeam;class YourUserInvitedToTeamListener{/**     * Create the event listener.     *     * @return void     */publicfunction__construct()    {//    }/**     * Handle the event.     *     * @param  UserInvitedToTeam  $event     * @return void     */publicfunctionhandle(UserInvitedToTeam$event)    {// $user = $event->getInvite()->user;// $teamId = $event->getTeamId();// Do something with the user and team ID.    }}

If your models are somehow limited to the current team you will find yourself writing this query over and over again:Model::where('team_id', auth()->user()->currentTeam->id)->get();.

To automate this process, you can let your models use theUsedByTeams trait. This trait will automatically append the current team id of the authenticated user to all queries and will also add it to a field calledteam_id when saving the models.

Note:

This assumes that the model has a field calledteam_id

Usage

useMpociot\Teamwork\Traits\UsedByTeams;class Taskextends Model{use UsedByTeams;}

When using this trait, all queries will appendWHERE team_id=CURRENT_TEAM_ID.If theres a place in your app, where you really want to retrieve all models, no matter what team they belong to, you can use theallTeams scope.

Example:

// gets all tasks for the currently active team of the authenticated userTask::all();// gets all tasks from all teams globallyTask::allTeams()->get();

Teamwork is free software distributed under the terms of the MIT license.

'Marvel Avengers' image licensed underCreative Commons 2.0 - Photo fromW_Minshull

About

User to Team associations with invitation system for the Laravel Framework

Topics

Resources

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.md

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp