如何在laravel中按日期连接两个不同的数组并显示顺序

I have two array named as payment and invoice. i need to display these arrays order by Invoice date and Payment Date ASC.

Controller Code :

$reqsales=Sales::Where('inv_date','>=',$request->input('frmdate_submit'))->Where('inv_date','<=',$request->input('todate_submit'))->Where('customer_id',$request->input('clients'))->get();


$reqpayments=Paymenttransaction::Where('transaction_date','>=',$request->input('frmdate_submit'))->Where('transaction_date','<=',$request->input('todate_submit'))->Where('transaction_category',1)->Where('transaction_type',2)->Where('transaction_cus_vendor',$request->input('clients'))->get();

View code is below

@foreach($reqsales as $sales)
<tr>
<td>{{date("d M Y",strtotime($sales->inv_date))}}</td>
<td>Invoice - {{$sales->inv_prefix.''.$sales->inv_no}}</td>
<td align="right"> {{number_format($sales->invoice_totalamt,2)}} @php $debitamt+=$sales->invoice_totalamt; @endphp</td>
<td></td>
 </tr>
@endforeach

@foreach($reqpayments as $payments)
<tr>
<td>{{date("d M Y",strtotime($payments->transaction_date))}}</td>
<td>Payment for {{$payments->sales->inv_prefix.''.$payments->sales->inv_no}}</td>
<td></td>
<td align="right">{{number_format($payments->transaction_amt,2)}} @php $creditamt+=$payments->transaction_amt; @endphp</td>
</tr>
@endforeach

Currently Displayed

enter image description here

Need to Display

enter image description here

You can't order by if you have two different arrays. In your current scenario, all your invoices gets printed before printing payment.

So, you have to handle this in a single Query, in the sense. You need to get all the data (both Invoice & Payment) in a single Query Builde like so,

$data = SomeCommonTable::leftJoin('invoice...')
                        ->leftJoin('payment...')
                        ->selectRaw(...)
                        ->orderBy('date','asc/desc)
                        ->get();

If you can't achieve like the above query, you need to unionAll with selectRaw same in both the queryBuilder, once you union it, you will be able to add orderBy('date','asc/desc') in your union query. You can refer to docs here for more details on union

If you want to do it from query then you have to simply use the union all where you can select the inv_date and transaction_date column in same row.

There is another way to do this in the php. You can use array method.

Use This:

$reqSalesPayments = array_merge($reqsales, $reqpayments);
$inv_date = array_column($reqsales, 'inv_date');
$transaction_date = array_column($reqpayments, 'transaction_date');

$arr = array_merge($inv_date, $transaction_date);
array_multisort($arr, SORT_ASC, $reqSalesPayments);

foreach($reqSalesPayments as $sales){
    //Print the table
}