Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active November 28, 2023 11:23
Show Gist options
  • Save MrPunyapal/0c8c4f9687c48c39038df99801b2b4ef to your computer and use it in GitHub Desktop.
Save MrPunyapal/0c8c4f9687c48c39038df99801b2b4ef to your computer and use it in GitHub Desktop.
Enhance Laravel Access Control with 'BelongsToTeam' Trait: Simplify Team-Based Permissions
<?php
namespace App\Traits\Models;
use App\Models\Team;
use Illuminate\Database\Eloquent\Builder;
trait BelongsToTeam
{
// This method is executed when a new model is being created.
public static function bootBelongsToTeam()
{
static::creating(function ($model) {
// Set the 'team_id' attribute of the model to the 'team_id' of the currently authenticated user.
$model->team_id = auth()->user()->team_id;
});
}
protected static function booted(): void
{
// Call the boot method of the parent class.
parent::booted();
// Check if a user is authenticated.
if (auth()->check()) {
// Add a global scope to the model to restrict queries to the user's team.
static::addGlobalScope('team', function (Builder $query) {
$query->team();
});
}
}
// This is a local scope that filters records based on the team.
public function scopeTeam(Builder $query)
{
return $query->when(auth()->user()->team_id,
function (Builder $query, $team_id) {
// Use `getTable()` to specify the table where the 'team_id' column is expected.
return $query->where(with(new static)->getTable().'.team_id', $team_id);
// if model is User::class then users.team_id it helpes when we are working with
// HasOneThrough or HasManyThrough or any join oprations.
},
function ($query) {
// If the user doesn't belong to any team, abort with a 403 Forbidden status.
abort(403);
return $query;
}
);
}
// Define a relationship between the model and the 'Team' model.
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