You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CurrentCompanyScope.php 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. $companyId = session('current_company_id');
  17. if (! $companyId && app()->runningInConsole()) {
  18. return;
  19. }
  20. if (! $companyId && Auth::check() && Auth::user()->currentCompany) {
  21. $companyId = Auth::user()->currentCompany->id;
  22. session(['current_company_id' => $companyId]);
  23. }
  24. if (! $companyId) {
  25. $companyId = Auth::user()->currentCompany->id;
  26. }
  27. if ($companyId) {
  28. $builder->where("{$model->getTable()}.company_id", $companyId);
  29. } else {
  30. Log::error('CurrentCompanyScope: No company_id found for user ' . Auth::id());
  31. throw new ModelNotFoundException('CurrentCompanyScope: No company_id set in the session or on the user.');
  32. }
  33. }
  34. }