Laravel 5.8: Display eloquent items sorted based on timestamp

As per my understanding, you have data that retrieved from multiple models.

So what you can do is to, merge the informations into a new array:

For example, consider the data regarding the ticket history is being stored in an array named:

$arrTicketHistory;

And consider, that the information regarding the ticket updates is being stored in an array named:

$arrTicketUpdates;

Merge these two arrays and assign the result in another array, say:

$arrDatesAndIDs;

Now try sorting the array $arrDatesAndIDs on the basis of timestamp i.e. created_at. Then display the result with a simple for loop.

You can add a custom parameter in the arrays $arrTicketUpdates and $arrDatesAndIDs, just for the sake of uniqueness. It might help you to identify which type of information it is, regarding the ticket.

You can use the array function array_msort(), a php function, to sort a multidimensional array.


I just found this answer, but this one has one big issue: It overwrites in worst-case some objects with different objects and this results in possible missing objects in the collection.

From the Laravel documentation: Collections:

The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection.

Due to this, I had to update the logic to this:

$ticket = Tickets::where('tracking_number', '=', $request->tracking_number)->first();
$comments = $ticket->comments;
$operations = $ticket->operations;
$history_unsorted = new Collection();
$history_unsorted = $history_unsorted->merge($comments);
$history_unsorted = $history_unsorted->merge($operations);
$history = $history_unsorted->sortBy('created_at');

This avoids, that the original collection gets overwritten.

With this, I can simply loop over $history:

@foreach($history as $history_item)
    @if ($history_item instanceof App\TicketOperations)
        <!-- Ticket Operation -->
    @else
        <!-- Ticket Comment (Text) -->
    @endif
@endforeach