Reputation: 2233
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);
}
Upvotes: 2
Views: 4781
Reputation: 8709
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()));
Upvotes: 2