2017 © Pedro Pelรกez
 

library teamwork

User to Team associations for the Laravel 5 Framework

image

mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  • Tuesday, March 20, 2018
  • by mpociot
  • Repository
  • 30 Watchers
  • 621 Stars
  • 37,608 Installations
  • PHP
  • 3 Dependents
  • 0 Suggesters
  • 85 Forks
  • 16 Open issues
  • 35 Versions
  • 14 % Grown

The README.md

Teamwork

This package supports Laravel 6 and above., (*1)

Latest Version Software License Build Status codecov.io SensioLabsInsight Scrutinizer Code Quality, (*2)

Teamwork is the fastest and easiest method to add a User / Team association with Invites to your Laravel 6+ project., (*3)

Installation

composer require mpociot/teamwork

The Teamwork Facade will be discovered by Laravel automatically., (*4)

Configuration

To publish Teamwork's configuration and migration files, run the vendor:publish command., (*5)

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

This will create a teamwork.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., (*6)

User relation to teams

Run the migration command, to generate all tables needed for Teamwork. If your users are stored in a different table other than users be sure to modify the published migration., (*7)

php artisan migrate

After the migration, 3 new tables will be created:, (*8)

  • teams โ€” stores team records
  • team_user โ€” stores many-to-many relations between users and teams
  • team_invites โ€” stores pending invites for email addresses to teams

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

Models

Team

Create a Team model inside app/Team.php using the following example:, (*10)

<?php namespace App;

use Mpociot\Teamwork\TeamworkTeam;

class Team extends TeamworkTeam
{
}

The Team model has two main attributes:, (*11)

  • owner_id โ€” Reference to the User model that owns this Team.
  • name โ€” Human readable name for the Team.

The owner_id is an optional attribute and is nullable in the database., (*12)

When extending TeamworkTeam, remember to change the team_model variable in config/teamwork.php to your new model. For instance: 'team_model' => App\Team::class, (*13)

User

Add the UserHasTeams trait to your existing User model:, (*14)

<?php namespace App;

use Mpociot\Teamwork\Traits\UserHasTeams;

class User extends Model {

    use UserHasTeams; // Add this trait to your model
}

This will enable the relation with Team and add the following methods teams(), ownedTeams() currentTeam(), invites(), isTeamOwner(), isOwnerOfTeam($team), attachTeam($team, $pivotData = []), detachTeam($team), attachTeams($teams), detachTeams($teams), switchTeam($team) within your User model., (*15)

Don't forget to dump composer autoload, (*16)

composer dump-autoload

Middleware

If you would like to use the middleware to protect to current team owner then just add the middleware provider to your app\Http\Kernel.php file., (*17)

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

Afterwards you can use the teamowner middleware in your routes file like so., (*18)

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., (*19)

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

And you are ready to go., (*21)

Usage

Scaffolding

The easiest way to give your new Laravel project Team abilities is by using the make:teamwork command., (*22)

php artisan make:teamwork

This command will create all views, routes and controllers to make your new project team-ready., (*23)

Out of the box, the following parts will be created for you:, (*24)

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

Imagine it as a the make:auth command for Teamwork., (*25)

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

Basic concepts

Let's start by creating two different Teams., (*27)

$team    = new Team();
$team->owner_id = User::where('username', '=', 'sebastian')->first()->getKey();
$team->name = 'My awesome team';
$team->save();

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

Now thanks to the UserHasTeams trait, assigning the Teams to the user is super easy:, (*28)

$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 the attachTeam method, if the User has no Teams assigned, the current_team_id column will automatically be set., (*29)

Alternatively, you can also use createOwnedTeam method from UserHasTeams trait. It will create team for the user as owner, attach the user to the team and switch to the newly created team., (*30)

// Create user owned team and switch the current team to this new team.
$team = $user->createOwnedTeam(['name' => 'My awesome team']);

// If user has another current team active, you should pass second parameter as true to force switch to the new team.
$team = $user->createOwnedTeam(['name' => 'My awesome team'], true);

The function will return the newly created instance of your team model., (*31)

Get to know my team(s)

The currently assigned Team of a user can be accessed through the currentTeam relation like this:, (*32)

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.";

The Team model has access to these methods:, (*33)

  • 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

Team owner

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

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:, (*35)

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

The isOwnerOfTeam method also allows an array or id as team parameter., (*36)

Switching the current team

If your Users are members of multiple teams you might want to give them access to a switch team mechanic in some way., (*37)

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!, (*38)

Glad we have the UserHasTeams trait., (*39)

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

Just like the isOwnerOfTeam method, switchTeam accepts a Team object, array, id or null as a parameter., (*40)

Inviting others

The best team is of no avail if you're the only team member., (*41)

To invite other users to your teams, use the Teamwork facade., (*42)

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 an email property like:, (*43)

$user = Auth::user();

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

This method will create a TeamInvite model and return it in the callable third parameter., (*44)

This model has these attributes:, (*45)

  • 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:, (*46)

  • user() โ€” one-to-one relation using the email 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: The inviteToTeam method will not check if the given email already has a pending invite. To check for pending invites use the hasPendingInvite method on the Teamwork facade., (*47)

Example usage:, (*48)

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
}

Accepting invites

Once you invited other users to join your team, in order to accept the invitation use the Teamwork facade once again., (*49)

$invite = Teamwork::getInviteFromAcceptToken( $request->token ); // Returns a TeamworkInvite model or null

if( $invite ) // valid token found
{
    Teamwork::acceptInvite( $invite );
}

The acceptInvite method does two thing:, (*50)

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

Denying invites

Just like accepting invites:, (*51)

$invite = Teamwork::getInviteFromDenyToken( $request->token ); // Returns a TeamworkInvite model or null

if( $invite ) // valid token found
{
    Teamwork::denyInvite( $invite );
}

The denyInvite method is only responsible for deleting the invitation from the database., (*52)

Attaching/Detaching/Invite Events

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:, (*53)

\Mpociot\Teamwork\Events\UserJoinedTeam

\Mpociot\Teamwork\Events\UserLeftTeam

\Mpociot\Teamwork\Events\UserInvitedToTeam

In your EventServiceProvider add your listener(s):, (*54)

/**
 * 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:, (*55)

<?php

namespace App\Listeners;

use Mpociot\Teamwork\Events\UserJoinedTeam;

class YourJoinedTeamListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserJoinedTeam  $event
     * @return void
     */
    public function handle(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:, (*56)

<?php

namespace App\Listeners;

use Mpociot\Teamwork\Events\UserInvitedToTeam;

class YourUserInvitedToTeamListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserInvitedToTeam  $event
     * @return void
     */
    public function handle(UserInvitedToTeam $event)
    {
        // $user = $event->getInvite()->user;
        // $teamId = $event->getTeamId();

        // Do something with the user and team ID.
    }
}

Limit Models to current Team

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();., (*57)

To automate this process, you can let your models use the UsedByTeams 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 called team_id when saving the models., (*58)

Note:, (*59)

This assumes that the model has a field called team_id, (*60)

Usage

use Mpociot\Teamwork\Traits\UsedByTeams;

class Task extends Model
{
    use UsedByTeams;
}

When using this trait, all queries will append WHERE 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 the allTeams scope., (*61)

Example:, (*62)

// gets all tasks for the currently active team of the authenticated user
Task::all();

// gets all tasks from all teams globally
Task::allTeams()->get();

License

Teamwork is free software distributed under the terms of the MIT license., (*63)

'Marvel Avengers' image licensed under Creative Commons 2.0 - Photo from W_Minshull, (*64)

The Versions

20/03 2018

dev-master

9999999-dev http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

27/01 2018

5.1.0

5.1.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

29/01 2017

5.0.0

5.0.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

19/11 2016

4.1.0

4.1.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

17/11 2016

4.0.3

4.0.3.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

13/11 2016

4.0.2

4.0.2.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

29/08 2016

4.0.1

4.0.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

25/08 2016

4.0.0

4.0.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

13/06 2016
31/05 2016
30/05 2016
27/05 2016
25/05 2016
22/05 2016
18/05 2016

3.1.3

3.1.3.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

18/05 2016

3.1.2

3.1.2.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

11/05 2016

3.1.1

3.1.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

10/05 2016

3.1.0

3.1.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

10/04 2016

3.0.1

3.0.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

18/03 2016

3.0.0

3.0.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

02/02 2016

2.0.1

2.0.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

04/01 2016

2.0.0

2.0.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

04/01 2016

dev-develop

dev-develop http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

29/08 2015

1.2.1

1.2.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

29/08 2015

1.2.0

1.2.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

07/08 2015

1.1.3

1.1.3.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

06/08 2015

1.1.2

1.1.2.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

04/08 2015

1.1.1

1.1.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

04/08 2015

1.1.0

1.1.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

03/08 2015

1.0.4

1.0.4.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

30/07 2015

1.0.3

1.0.3.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

30/07 2015

1.0.2

1.0.2.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

30/07 2015

1.0.1

1.0.1.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

29/07 2015

1.0.0

1.0.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams

07/07 2015

0.7.0

0.7.0.0 http://github.com/mpociot/teamwork

User to Team associations for the Laravel 5 Framework

  Sources   Download

MIT

The Requires

 

The Development Requires

invite teams