Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

CompanyOwned.php 1.8KB

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