Files
sam-manage/app/Models/Scopes/TenantScope.php
김보곤 f405c690a4 fix: [tenant] TenantScope에 session selected_tenant_id fallback 추가
- users 테이블에 tenant_id 컬럼이 없어 글로벌 스코프 미작동
- session('selected_tenant_id') fallback으로 테넌트 필터링 정상화
- 결재 양식 등 모든 BelongsToTenant 모델에 영향
2026-03-05 19:08:25 +09:00

56 lines
1.4 KiB
PHP

<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Http\Request;
class TenantScope implements Scope
{
/**
* 캐시된 tenant_id (요청당 한 번만 조회)
*/
private static ?int $cachedTenantId = null;
private static bool $cacheInitialized = false;
/**
* Apply the scope to a given Eloquent query builder.
*/
public function apply(Builder $builder, Model $model)
{
// artisan migrate 등은 제외
if (app()->runningInConsole()) {
return;
}
// 캐시된 tenant_id가 없으면 조회 (요청당 1회만)
if (! self::$cacheInitialized) {
$request = app(Request::class);
self::$cachedTenantId = $request->attributes->get('tenant_id')
?? $request->header('X-TENANT-ID')
?? session('selected_tenant_id')
?? auth()->user()?->tenant_id;
self::$cacheInitialized = true;
}
if (self::$cachedTenantId !== null) {
$builder->where($model->getTable().'.tenant_id', self::$cachedTenantId);
}
}
/**
* 캐시 초기화 (테스트 또는 장기 실행 프로세스에서 필요 시)
*/
public static function clearCache(): void
{
self::$cachedTenantId = null;
self::$cacheInitialized = false;
}
}