where('is_deleted', 0) ->pluck('company_id'); Invoice::query() ->where('invoices.is_deleted', false) ->whereNull('invoices.deleted_at') ->whereNotNull('invoices.due_date') ->whereIn('invoices.status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('invoices.balance', '>', 0) ->whereIn('invoices.company_id', $company_ids) // ->whereHas('client', function ($query) { // $query->where('is_deleted', 0) // ->where('deleted_at', null); // }) // ->whereHas('company', function ($query) { // $query->where('is_disabled', 0); // }) ->leftJoin('clients', function ($join) { $join->on('invoices.client_id', '=', 'clients.id') ->where('clients.is_deleted', 0) ->whereNull('clients.deleted_at'); }) ->leftJoin('companies', function ($join) { $join->on('invoices.company_id', '=', 'companies.id') ->where('companies.is_disabled', 0); }) ->whereBetween('invoices.due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) ->cursor() ->each(function ($invoice) { (new WebhookHandler(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client'))->handle(); }); } else { foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); $company_ids = Webhook::where('event_id', Webhook::EVENT_LATE_INVOICE) ->where('is_deleted', 0) ->pluck('company_id'); Invoice::query() ->where('invoices.is_deleted', false) ->whereNull('invoices.deleted_at') ->whereNotNull('invoices.due_date') ->whereIn('invoices.status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('invoices.balance', '>', 0) ->whereIn('invoices.company_id', $company_ids) // ->whereHas('client', function ($query) { // $query->where('is_deleted', 0) // ->where('deleted_at', null); // }) // ->whereHas('company', function ($query) { // $query->where('is_disabled', 0); // }) ->leftJoin('clients', function ($join) { $join->on('invoices.client_id', '=', 'clients.id') ->where('clients.is_deleted', 0) ->whereNull('clients.deleted_at'); }) ->leftJoin('companies', function ($join) { $join->on('invoices.company_id', '=', 'companies.id') ->where('companies.is_disabled', 0); }) ->whereBetween('invoices.due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) ->cursor() ->each(function ($invoice) { (new WebhookHandler(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client'))->handle(); }); } } } }