如何使用Laravel Event发送电子邮件?

时间:2016-10-09 08:39:49

标签: php laravel laravel-5

我创建了一个活动。在创建项目时,会向该项目所有者发送一封电子邮件。我创建了一个事件和一个监听器。但我可以将数据存储在数据库中。但是我没有收到邮件。我收到以下错误:

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

这是我的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');
    }
}

这里是监听器(SendMailFired.php)部分:

<?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');
        });
    }
}

这是控制器部分:

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);
            }

1 个答案:

答案 0 :(得分:2)

这可能是一个错字,但我认为

 let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tabcontroller") as! UITabbarController
  self.presentViewController(viewController, animated: true, completion: nil)

必须改为

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

您还可以将整个项目传递给事件构造函数,以避免额外的数据库调用。

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