function syncVoucher($vouchers) { if (!$this->attributes) { return false; } //////////////////////////////// // Add address to this object // //////////////////////////////// foreach ($vouchers as $k => $voucher) { if ($voucher instanceof Voucher) { ////////////// // Validate // ////////////// $observer = new \App\Models\VoucherObserver(); if ($observer->saving($voucher) === false) { $this->setErrors($voucher->getErrors()); return false; } } } ///////////////////////////////////////////////////////////////// // Check if there's a deletion on voucher that has been issued // ///////////////////////////////////////////////////////////////// if ($this->vouchers->count()) { foreach ($this->vouchers as $voucher) { //////////////////////////////////////////////////////// // Check if old voucher is missing in current voucher // //////////////////////////////////////////////////////// $still_in_voucher_list = false; foreach ($vouchers as $new_voucher) { if ($new_voucher->_id == $voucher->_id) { $still_in_voucher_list = true; } } ////////////////////////////////////////////////// // For missing voucher, check if already issued // ////////////////////////////////////////////////// if (!$still_in_voucher_list) { if (IssuedVoucher::ScheduleId($this->_id)->voucherId($voucher->_id)->count()) { $this->setErrors(new MessageBag(['voucher.' . $k => 'Unable to delete voucher ' . $k . ' as it has issued voucher'])); return false; } } } } ////////////////////////////////////////////////////////////////// // Check if there's changes on voucher that already been issued // ////////////////////////////////////////////////////////////////// foreach ($vouchers as $k => $voucher) { if ($voucher->isDirty()) { if (IssuedVoucher::ScheduleId($this->_id)->voucherId($voucher->id)->count()) { $this->setErrors(new MessageBag(['voucher.' . $k => 'Unable to update voucher ' . $k . ' as it has issued voucher'])); return false; } } } //////////////////////////// // Delete current address // //////////////////////////// foreach ($this->vouchers as $voucher) { $this->vouchers()->dissociate($voucher); } /////////////////////////// // Associate all address // /////////////////////////// $vouchers = array_sort($vouchers, function ($value) { return $value->since; }); foreach ($vouchers as $voucher) { $this->vouchers()->associate($voucher); } return true; }