Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CompanyOwned.php 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Concerns;
  3. use App\Models\Notification;
  4. use App\Models\User;
  5. use App\Scopes\CurrentCompanyScope;
  6. use Illuminate\Database\Eloquent\ModelNotFoundException;
  7. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\Log;
  10. use Wallo\FilamentCompanies\FilamentCompanies;
  11. trait CompanyOwned
  12. {
  13. public static function bootCompanyOwned(): void
  14. {
  15. static::creating(static function ($model) {
  16. if (empty($model->company_id)) {
  17. $companyId = session('current_company_id');
  18. if (! $companyId && ($user = Auth::user()) && ($companyId = $user->current_company_id)) {
  19. session(['current_company_id' => $companyId]);
  20. }
  21. // For notifications in job context, get company_id from the notifiable user
  22. if (! $companyId && $model instanceof Notification && $model->notifiable_type === User::class) {
  23. $notifiable = $model->notifiable;
  24. if ($notifiable instanceof User) {
  25. $companyId = $notifiable->current_company_id;
  26. }
  27. }
  28. if ($companyId) {
  29. $model->company_id = $companyId;
  30. } else {
  31. Log::error('CurrentCompanyScope: No company_id found for user ' . Auth::id());
  32. throw new ModelNotFoundException('CurrentCompanyScope: No company_id set in the session, user, or database.');
  33. }
  34. }
  35. });
  36. static::addGlobalScope(new CurrentCompanyScope);
  37. }
  38. public function company(): BelongsTo
  39. {
  40. return $this->belongsTo(FilamentCompanies::companyModel(), 'company_id');
  41. }
  42. }