class Customer extends Model { // ... public function created_by() { return $this->belongsTo(User::class, 'created_by_id'); } }
trait MultiTenantModelTrait { public static function bootMultiTenantModelTrait() { if (!app()->runningInConsole() && auth()->check()) { $isAdmin = auth()->user()->roles->contains(1); static::creating(function ($model) use ($isAdmin) { // Prevent admin from setting his own id - admin entries are global. // If required, remove the surrounding IF condition and admins will act as users if (!$isAdmin) { $model->created_by_id = auth()->id(); } }); if (!$isAdmin) { static::addGlobalScope('created_by_id', function (Builder $builder) { $builder->where('created_by_id', auth()->id())->orWhereNull('created_by_id'); }); } } } }The code here may look complicated, but the logic is simple - whether to add global scope or not.
use App\Traits\MultiTenantModelTrait; class Customer extends Model { use SoftDeletes, MultiTenantModelTrait; // ...
class User extends Authenticatable { // ... public function team() { return $this->belongsTo(Team::class, 'team_id'); } }
trait MultiTenantModelTrait { public static function bootMultiTenantModelTrait() { if (!app()->runningInConsole() && auth()->check()) { $isAdmin = auth()->user()->roles->contains(1); static::creating(function ($model) use ($isAdmin) { if (!$isAdmin) { $model->team_id = auth()->user()->team_id; } }); if (!$isAdmin) { static::addGlobalScope('team_id', function (Builder $builder) { $field = sprintf('%s.%s', $builder->getQuery()->from, 'team_id'); $builder->where($field, auth()->user()->team_id)->orWhereNull($field); }); } } } }
User::withoutGlobalScopes()->get();
If you can't find what you're looking for, use live-chat on bottom-right or email us info@laraveldaily.com