简体   繁体   中英

How to send Email using Laravel Event?

I have created a event.Where when a Items been created, an email will send to that item owner. I have created a Event and a listener.But I can store the data in database.But I didn't get the mail. I got the following Error:

 FatalThrowableError in SendMailFired.php line 31: Call to a member function toArray() on null

Here is my Event SendMail.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class SendMail
{
    use InteractsWithSockets, SerializesModels;
    public $id;


    public function __construct($id)
    {
        $this->id = $id;
    }


    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

here is the listener (SendMailFired.php) part:

<?php

namespace App\Listeners;

use App\Events\SendMail;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Item;
use Mail;

class SendMailFired
{

    public function __construct()
    {

    }

    public function handle(SendMail $event)
    {
          $item = Item::find($event->id)->toArray();

          Mail::send('send', $item, function($message) use ($item) {
            $message->to($item['email']);
            $message->subject('Event Testing');
        });
    }
}

And here is the controller part :

public function store(Request $request)
            {
                $item= new Item();
                $item->title = $request->input(['title']);
                $item->description=$request->input(['description']);
                $item->email = $request->input(['email']);
                $item->status = '0';
                $item->save();
                 Event::fire(new SendMail('id'));
                return Response::json($item);
            }

It might be a typo, but I think

Event::fire(new SendMail('id'));

has to be changed into

Event::fire(new SendMail($item->id));

You could also pass the whole item to the event constructor, in order to avoid an additional database call.

Event::fire(new SendMail($item->toArray()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM