attributes['internal_id'] = 'TN-INR-'.$model->id; // Associate all relevant invoices $invoices = Invoice::whereBetween('date', [$model->date_start, $model->date_end]) ->where('customer_id', $model->customer_id); $model->invoices()->sync($invoices->pluck('id')->toArray()); $model->total = $model->invoices()->sum('total'); // Finally, save $model->save(); }); } public function customer(): BelongsTo { return $this->belongsTo(Customer::class); } public function invoices(): BelongsToMany { return $this->BelongsToMany(Invoice::class); } public function orders() { return $this->invoices()->with('orders')->get()->pluck('orders')->flatten()->unique('id'); } }