Managing users and teams in Laravel

by Marcel Pociot — on

cover-image

Team management is hard

If you're building a product, for example a SaaS as a side project, you might come to a point where you need more than the basic Authentication handling from Laravel.

For me, this happened when working on FileHero. We decided that we need "Teams" - like Bitbucket or Slack. Users can be assigned to multiple teams, team owners can invite more team members, delete other members and maybe have access to other features in your application.

So you start writing your models, controllers and repositories. You add relations to your authenticating model. You need to take care of handling the invites. You need to add the ACL related stuff and so on and so forth.

As every good programmer is lazy - and to quote Bill Gates:

'I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.'

I started working on a new Laravel package with a catchy name - Teamwork.

So initially it all started to become more of a personal package as I didn't want to write the whole team management code for the next project again.

Then came Laracon

So I was happily developing my package, posted it to Twitter and Reddit where Taylor Otwell replied and said it's a cool package.

So I thought: Great - I'm on the right track.

A few days later, I was watching Taylor Otwell's keynote at Laracon US and he was presenting "Laravel Spark" - where the alpha version was released today.

So long story short: Spark itself has integrated Team management. But - you can't only use the Team management from Spark. So that's where Teamwork comes in again.

Avengers Assemble!

Using a User to Team association with Teamwork is really easy. Just let your Authenticable Model use the UserHasTeam trait.

<?php namespace App;

use Mpociot\Teamwork\Traits\UserHasTeams;

class User extends Model {

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

This allows you to handle everything related to teams.

Some examples:

Add a Team to a User

$team = Team::create([
    "name" => "Internal team"
]);

Auth::user()->attachTeam( $team );

Get the user teams

// Get all teams of the User
Auth::user()->teams

// Get all teams which the user "owns"
Auth::user()->ownedTeams

Inviting others

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

To invite other users to your teams, use the Teamwork facade.

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

Future

That's the basic usage of my package. I hope you like it and can use it on your next project!

I would really love to get your feedback on the package and if you're already using Teamwork please let me know!