Установить «статус = отправлено» в таблице после отправки электронной почты в Laravel

#php #mysql #laravel #eloquent #laravel-7

#php #mysql #laravel #красноречивый #laravel-7

Вопрос:

Мое приложение отправляет каналы пользователям по электронной почте. Для этого я создал одно имя команды SendFeedEmails.php чтобы отправить электронное письмо.

Приведенная выше команда получит все каналы за сегодняшний день и сохранит user_id в массиве и выполнит закрытую функцию с именем sendEmailToUser.

С помощью этой функции все данные будут отправляться в почтовый класс FeedEmailDigest.

Но я хочу установить статус как отправленный в таблице с именем feed_statuses после отправки электронной почты пользователям.

  1. SendFeedEmails.php (Команда)
 <?php

namespace AppConsoleCommands;

use AppUser;
use AppFeedStatus;
use AppMailFeedEmailDigest;
use IlluminateConsoleCommand;
use IlluminateSupportFacadesMail;

class SendFeedEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'feed:emails';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send email notification to users about feeds.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Get all feeds for today
        $feeds = FeedStatus::query()
            ->with(['feeds'])
            ->where('msg_date', now()->format('Y-m-d'))
            ->where('status', 'pending')
            ->orderBy('user_id')
            ->get();

        // Group by user
        $data = [];
        foreach ($feeds as $feed) {
            $data[$feed->user_id][] = $feed->toArray();
        }

        //dd($data);

        foreach ($data as $userId => $feeds) {
            $this->sendEmailToUser($userId, $feeds);

        }
        
        // Send email
        return 0;
    }

    private function sendEmailToUser($userId, $feeds)
    {
        $user = User::find($userId);
        Mail::to($user)->send(new FeedEmailDigest($feeds));
    }
}
 
  1. FeedEmailDigest.php (Почта)
 <?php

namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;

class FeedEmailDigest extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    private $feeds;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($feeds)
    {
        $this->feeds = $feeds;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('emails.feed-digest')
            ->with('feeds', $this->feeds);
    }
}
 
  1. feed_statuses (таблица)

введите описание изображения здесь

Комментарии:

1. При фактической отправке электронной почты происходит событие (описано в руководстве ), однако мне неясно, с какими аргументами запускается событие. он получает Swit_Message экземпляр, а также некоторые данные, но вам может потребоваться сначала зарегистрировать это где-нибудь, чтобы посмотреть, какие данные у него есть, чтобы определить, как вывести правильную строку для обновления из нее (поскольку рассылка находится в очереди)

Ответ №1:

Попробуйте следующее

Отредактируйте функцию отправки почты, чтобы она стала..

     private function sendEmailToUser($userId, $feeds)
    {
        $user = User::find($userId);
        //Since you expect to have more than one entry for same user eg. feed 1 user 1, feed 2 user 1,   a loop will be in order
        foreach($feeds as $feed){
          $affected = DB::table('feed_statuses')->where(['user_id'=> $userId , 'feed_id' => $feed->id])->update(['status' => 'sent']);
        }
        Mail::to($user)->send(new FeedEmailDigest($feeds));

    }
 

Комментарии:

1. показывает ошибку. «Попытка получить свойство ‘id’ не-объекта»

2. Просто измените ‘feed_id’ => $feed-> id на ‘feed_id’ => $feed[‘feed_id’]