Laravel PHP: Get values out of Recursion Function

I have a invoice_schedule_table which is structured like:
id, previous_invoice_schedule_id, due_date
7559, , 01-06-2021
7772, 7559, 15-06-2021
7773, 7772, 20-06-2021

I am trying to create a looping/recursive function which will ultimately give me back the last due_date (20-06-2021) if I am opening up any invoice schedule(ID: 7559, 7772) from the UI.

function latestRescheduledInvoiceSchedule($invoiceScheduleId) {

    $rescheduledPaymentSchedule = InvoiceSchedule::where('previous_invoice_schedule_id', $invoiceScheduleId)->first();

    if(isset($rescheduledPaymentSchedule)) {
        latestRescheduledInvoiceSchedule($rescheduledPaymentSchedule->id);
    }
}

But I am unable to figure out how to get the value once it reaches the last record.

Any help regarding this?

2 answers

  • answered 2021-05-14 15:59 nice_dev

    No need of recursive function. You can just use a loop of your choice to get the latest row like below:

    <?php
    
    
    function latestRescheduledInvoiceSchedule($invoiceScheduleId) {
        $payment_schedule_row = '';
        $rescheduledPaymentSchedule = '';
        do{
            $invoiceScheduleId = $rescheduledPaymentSchedule->id ?? $invoiceScheduleId;
            $payment_schedule_row = $rescheduledPaymentSchedule ?? '';
            $rescheduledPaymentSchedule = InvoiceSchedule::where('previous_invoice_schedule_id', $invoiceScheduleId)->first();
        }while(!empty($rescheduledPaymentSchedule));
    
        
        if(empty($payment_schedule_row)){
            $payment_schedule_row = InvoiceSchedule::find($invoiceScheduleId);
        }
        // rest of the code goes here
        dd($payment_schedule_row);  
    }
    

  • answered 2021-05-14 16:01 Luca Pizzini

    You should retrieve the due_date value when the $rescheduledPaymentSchedule is not set, in this case it will be with an id of 7773:

    function latestRescheduledInvoiceSchedule($invoiceScheduleId) {
        $rescheduledPaymentSchedule = InvoiceSchedule::where('previous_invoice_schedule_id', $invoiceScheduleId)->first();
    
        if($rescheduledPaymentSchedule) {
            latestRescheduledInvoiceSchedule($rescheduledPaymentSchedule->id);
        } else {
            // There is no further values, retrieve the `due_date` of the current invoiceScheduleId
            $last_record = InvoiceSchedule::find($invoiceScheduleId);
            if ($last_record) {
                $last_due_date = $last_record->due_date;
            }
        }
    }