Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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. $companyId = session('current_company_id');
  17. if (! $companyId && app()->runningInConsole()) {
  18. return;
  19. }
  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. }