Blame view

app/Observers/Company.php 1.47 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
  <?php
  
  namespace App\Observers;
  
  use App\Models\Common\Company as Model;
  use Artisan;
  use Auth;
  
  class Company
  {
      /**
       * Listen to the created event.
       *
       * @param  Model  $company
       * @return void
       */
      public function created(Model $company)
      {
          // Create seeds
          Artisan::call('company:seed', [
              'company' => $company->id
          ]);
  
          // Check if user is logged in
          if (!Auth::check()) {
              return;
          }
  
          // Attach company to user
          Auth::user()->companies()->attach($company->id);
      }
  
      /**
       * Listen to the deleted event.
       *
       * @param  Model  $company
       * @return void
       */
      public function deleted(Model $company)
      {
          $tables = [
              'accounts', 'bill_histories', 'bill_items', 'bill_payments', 'bill_statuses', 'bills', 'categories',
              'currencies', 'customers', 'invoice_histories', 'invoice_items', 'invoice_payments', 'invoice_statuses',
              'invoices', 'items', 'payments', 'recurring', 'revenues', 'settings', 'taxes', 'transfers', 'vendors',
          ];
  
          foreach ($tables as $table) {
              $this->deleteItems($company, $table);
          }
      }
  
      /**
       * Delete items in batch.
       *
       * @param  Model  $company
       * @param  $table
       * @return void
       */
      protected function deleteItems($company, $table)
      {
          foreach ($company->$table as $item) {
              $item->delete();
          }
      }
  }