To handle the reordering of the approvals in the pivot table, you need to adjust the order column for the affected rows. When moving an approval up or down, you should swap the order values of the two adjacent rows. Here's how you can implement the moveApprovalUp and moveApprovalDown methods:
public function moveApprovalUp($approval)
{
$currentOrder = $approval['pivot']['order'];
// Find the approval directly above
$previousApproval = $this->purchaseRequestType->typeApprovals()
->wherePivot('order', '<', $currentOrder)
->orderByPivot('order', 'desc')
->first();
if ($previousApproval) {
// Swap the order values
$this->purchaseRequestType->typeApprovals()->updateExistingPivot($approval['pivot']['pr_type_approval_id'], [
'order' => $previousApproval->pivot->order,
]);
$this->purchaseRequestType->typeApprovals()->updateExistingPivot($previousApproval->pivot->pr_type_approval_id, [
'order' => $currentOrder,
]);
}
}
public function moveApprovalDown($approval)
{
$currentOrder = $approval['pivot']['order'];
// Find the approval directly below
$nextApproval = $this->purchaseRequestType->typeApprovals()
->wherePivot('order', '>', $currentOrder)
->orderByPivot('order', 'asc')
->first();
if ($nextApproval) {
// Swap the order values
$this->purchaseRequestType->typeApprovals()->updateExistingPivot($approval['pivot']['pr_type_approval_id'], [
'order' => $nextApproval->pivot->order,
]);
$this->purchaseRequestType->typeApprovals()->updateExistingPivot($nextApproval->pivot->pr_type_approval_id, [
'order' => $currentOrder,
]);
}
}
In the moveApprovalUp method, you find the approval that is directly above the current one by looking for the nearest lower order value. If such an approval exists, you swap their order values.
Similarly, in the moveApprovalDown method, you find the approval that is directly below the current one by looking for the nearest higher order value and swap their order values if it exists.
Make sure to refresh the $approvals collection after performing these operations to reflect the new order in your Livewire component's view. You can do this by reassigning the $approvals property:
$this->approvals = $this->purchaseRequestType->typeApprovals()->orderBy('pivot_order')->get();
This will ensure that the UI is updated with the new order of approvals.