UsedByTeams
Model Trait For Laravel Spark
So you're using spark, and you have teams enabled. You start creating models and want to have them be team specific. Instead of writing, Model::where('team_id', auth()->user()->currentTeam->id)->get();
use this trait to add that behind the scenes so that every time you call on your model, it's assumed that you mean for the current team.
This assumes that the model has a team_id
, while it adds a scope of where team_id = currentTeam->id
.
Make a file, namespaced etc
Add use UsedByTeams
to your model
Simply add allTeams
to your query, Model::allTeams()->get()
and the model won't be limited by the current team
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
trait UsedByTeams
{
protected static function boot()
{
parent::boot();
if(! auth()->guest())
{
static::addGlobalScope('team', function(Builder $builder)
{
$builder->where('team_id', auth()->user()->currentTeam->id);
});
}
}
public function scopeAllTeams($query)
{
return $query->withoutGlobalScope('team');
}
public function team()
{
return $this->belongsTo('App\Team');
}
}
I also added the ability to access the team from the model, like $model->team()->name
etc
The Model
<?php
namespace App;
use App\Traits\UsedByTeams;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use UsedByTeams;
}
Usage
Task::all(); // gets all the teams tasks
Task::allTeams()->get(); // gets all tasks
//-------
$tasks = Task::allTeams()->get();
foreach($tasks as $task)
{
// get team associated with the task
$taskTeam = $task->team()->name;
}
First off: thanks for sharing this, it's been super helpful!
I've run into an issue with it where trying to do things via API or with artisan commands returns this:
Commenting out most of
UsedByTeams.php
resolves the issue, but obviously that's a kludgy workaround that is best avoided. Do you have any tips on how to more selectively apply or disable the trait so this isn't an issue?