Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Created December 1, 2023 05:04
Show Gist options
  • Save AnandPilania/a47858d74ba813f11acb675c3c92a036 to your computer and use it in GitHub Desktop.
Save AnandPilania/a47858d74ba813f11acb675c3c92a036 to your computer and use it in GitHub Desktop.
Laravel: Simplify Access Controller with BelongsToTeam
<?php
namespace App\Concerns;
use App\Models\Team;
use Illuminate\Database\Eloquent\Builder;
trait BelongsToTeam
{
public static function boot()
{
parent::boot();
if (!method_exists(static::class, 'bootTraits')) {
static::bootBelongsToTeam();
}
}
public static function bootBelongsToTeam()
{
static::creating(function ($model) {
$model->team_id = auth()->user()->team_id;
});
}
protected static function booted(): void
{
parent::booted();
if (auth()->check()) {
static::addGlobalScope('team', function (Builder $query) {
$query->team();
});
}
}
public function scopeTeam(Builder $query)
{
return $query->when(auth()->user()->team_id,
function (Builder $query, $team_id) {
return $query->where(with(new static)->getTable().'.team_id', $team_id);
},
function ($query) {
abort(403);
return $query;
}
);
}
public function team()
{
return $this->belongsTo(Team::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment