Laravel Imap Get Messages Sorted By Most Recent

- 1 answer

I am using laravel-imap to retrieve messages from a mailbox:

$aMessage = $selectedFolder->query()->setFetchFlags(true)->setFetchBody(true)->setFetchAttachment(false)->leaveUnread()
->limit(40, $highest_page)->get();

On default the most recent messages are on the highest page. If I simply get all messages and display them as they are I see the old ones first (page 1).

What I tried so far:

After I call ->get() the results can be treated as a normal laravel collection, but I had no success with these methods:

$aMessage = $aMessage->sortByDesc('date')->values()->all();

$aMessage = $aMessage->sortByDesc(function ($item) {
    //\Log::info(print_r($item, true));
    return $item->date;

I am sure the methods above do not work because I use ->limit(40, $highest_page), which means the collection has a size of 40.

If I dont limit the results and use slice I encounter a timeout error, because there are too many messages in the mailbox:

$aMessage = $selectedFolder->query()->setFetchFlags(true)->setFetchBody(true)->setFetchAttachment(false)->leaveUnread()
->get()->reverse()->slice(0, $messages_per_page);

I also tried laravel-imap's method paginate(). The results were the same as with limit().

At this point I am sure I have to sort somehow before the results turn into a collection. I also found:

'options' => [
    'fetch_order' => 'desc',

The options are added to the Client. I tried asc and desc. I also cleared config cache, but nothing works.

I still see the oldest results on page 1 and the most recent at the end.

Someone has more ideas?



After playing around with several solutions I decided to go into the vendor file (config/imap.php) and change the fetch_order there:

'fetch_order' => 'desc'

It was asc on default. It seems that changing the fetch_order when creating the client does not override the config. I had this before and it did not work, also no errors were thrown:

$this->oClient = new Client([
    'host'          => env('MAIL_HOST_IN'),
    'port'          => env('MAIL_PORT_IN'),
    'encryption'    => env('MAIL_ENCRYPTION_IN'),
    'validate_cert' => true,
    'username'      => env('MAIL_USERNAME'),
    'password'      => env('MAIL_PASSWORD'),
    'protocol'      => 'imap',
    'options' => [
        'fetch_order' => 'desc',