您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CurrentCompanyScope.php 1.1KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. namespace App\Scopes;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\ModelNotFoundException;
  6. use Illuminate\Database\Eloquent\Scope;
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Log;
  9. class CurrentCompanyScope implements Scope
  10. {
  11. /**
  12. * Apply the scope to a given Eloquent query builder.
  13. */
  14. public function apply(Builder $builder, Model $model): void
  15. {
  16. if (app()->runningInConsole()) {
  17. return;
  18. }
  19. $companyId = session('current_company_id');
  20. if (! $companyId && ($user = Auth::user()) && ($companyId = $user->current_company_id)) {
  21. session(['current_company_id' => $companyId]);
  22. }
  23. if ($companyId) {
  24. $builder->where("{$model->getTable()}.company_id", $companyId);
  25. } else {
  26. Log::error('CurrentCompanyScope: No company_id found for user ' . Auth::id());
  27. throw new ModelNotFoundException('CurrentCompanyScope: No company_id set in the session or on the user.');
  28. }
  29. }
  30. }