Blame view

app/Scopes/Company.php 1.79 KB
b7c7a5f6   Alexey Boroda   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  <?php
  
  namespace App\Scopes;
  
  use App;
  use Illuminate\Database\Eloquent\Scope;
  use Illuminate\Database\Eloquent\Model;
  use Illuminate\Database\Eloquent\Builder;
  
  class Company implements Scope
  {
      /**
       * Apply the scope to a given Eloquent query builder.
       *
       * @param  \Illuminate\Database\Eloquent\Builder  $builder
       * @param  \Illuminate\Database\Eloquent\Model  $model
       * @return void
       */
      public function apply(Builder $builder, Model $model)
      {
          $company_id = session('company_id');
          if (empty($company_id)) {
              return;
          }
  
          $table = $model->getTable();
  
          // Skip for specific tables
          $skip_tables = ['companies', 'jobs', 'migrations', 'notifications', 'permissions', 'role_user', 'roles', 'sessions', 'users'];
          if (in_array($table, $skip_tables)) {
              return;
          }
  
          // Skip if already exists
          if ($this->exists($builder, 'company_id')) {
              return;
          }
  
          // Apply company scope
          $builder->where($table . '.company_id', '=', $company_id);
      }
  
      /**
       * Check if scope exists.
       *
       * @param  \Illuminate\Database\Eloquent\Builder  $builder
       * @param  $column
       * @return boolean
       */
      protected function exists($builder, $column)
      {
          $query = $builder->getQuery();
  
          foreach ((array) $query->wheres as $key => $where) {
              if (empty($where) || empty($where['column'])) {
                  continue;
              }
  
              if (strstr($where['column'], '.')) {
                  $whr = explode('.', $where['column']);
  
                  $where['column'] = $whr[1];
              }
  
              if ($where['column'] != $column) {
                  continue;
              }
  
              return true;
          }
  
          return false;
      }
  }