HEX
Server: LiteSpeed
System: Linux s3604.bom1.stableserver.net 4.18.0-513.11.1.lve.el8.x86_64 #1 SMP Thu Jan 18 16:21:02 UTC 2024 x86_64
User: dmstechonline (1480)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /home/dmstechonline/whatsapp.dmstech.online/app/Console/Commands/UpdateLatestChatCreatedAt.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Contact;
use App\Models\Chat;

class UpdateLatestChatCreatedAt extends Command
{
    protected $signature = 'contacts:update-latest-chat-created-at';
    protected $description = 'Update latest_chat_created_at for existing contacts';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        Contact::with('chats')
            ->chunkById(100, function ($contacts) {
                foreach ($contacts as $contact) {
                    $latestChat = $contact->chats()->orderBy('created_at', 'desc')->first();
                    if ($latestChat) {
                        $contact->latest_chat_created_at = $latestChat->created_at;
                        $contact->save();
                    }
                }
            });

        $this->info('Latest chat created_at updated successfully for all contacts.');
    }
}