Skip to content

Instantly share code, notes, and snippets.

@TaffarelXavier
Last active November 2, 2022 03:15
Show Gist options
  • Select an option

  • Save TaffarelXavier/50777611e4a2b27cfe8d5ea9943f0572 to your computer and use it in GitHub Desktop.

Select an option

Save TaffarelXavier/50777611e4a2b27cfe8d5ea9943f0572 to your computer and use it in GitHub Desktop.

Trabalhando com eventos, listeres e filas no Laravel

"Um work (trabalhador) de fila é um processo regular que é executado em segundo plano e pesquisa o back-end da fila em busca de trabalhos não processados. Para iniciar um novo trabalhador, execute o comando php artisan queue:work dentro do diretório do seu projeto. O work (trabalhador) iniciará e começará processar o(s) trabalho(s) não processado(s) imediatamente." 1

1.php artisan make:mail PostCommentedMail --markdown=emails.posts.new-comment.blade

namespace App\Mail;
 
use App\Models\Comment;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
 
class PostCommentedMail extends Mailable
{
    use Queueable, SerializesModels;
 
    public $comment;
 
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(Comment $comment)
    {
        $this->comment = $comment;
    }
 
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
                    ->subject('Novo Comentário')
                    ->markdown('mails.posts.new-comment');
    }
}
  1. Editar este arquivo: resources/views/mails/posts/new-comment.blade.php
@component('mail::message')
 
{{ $comment->body }}
 
@component('mail::button', ['url' => route('posts.show', $comment->post->id)])
Ver Comentário: {{ $comment->post->title }}
@endcomponent
 
Obrigado,<br>
{{ config('app.name') }}
@endcomponent
  1. Listener Enviar o E-mail

Agora que já preparamos a nossa classe de envio de e-mail, precisa fazer o Listener SendMailCommentedPost enviar o e-mail, no método handle(), adicione este conteúdo:

/**
 * Handle the event.
 *
 * @param  CommentedPost  $event
 * @return void
 */
public function handle(CommentedPost $event)
{
    // Registring log commented post
    // Log::info($event->comment());
    $comment = $event->comment();
 
    Mail::to($comment->post->user->email)
                ->send(new PostCommentedMail($comment));
}

Dispatch event simple

event(new UpdatedServiceEvent($row));

REFERÊNCIAS

  1. https://blog.especializati.com.br/aprenda-como-trabalhar-com-eventos-no-laravel/
  2. https://blog.especializati.com.br/eventos-no-laravel-parte-2/
  3. https://www.honeybadger.io/blog/laravel-queues-deep-dive/ 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment