I am trying to send an email in background to reduce server response time.
I have created jobs table and failed_jobs table with using php artisan queue:table
and php artisan queue:failed-table
commands. and also set QUEUE_DRIVER=database
in .env file.
When I execute following code it creates a job in jobs table.
\Mail::later(5, 'email.new-friend-request', ['data'=>$friend_request], function($message) use (&$friend_request){
$message->to($friend_request->notifiable->email, $friend_request->notifiable->name)->from('info@example.com','ABC')->subject('New Friend Request');
});
But when I execute php artisan queue:listen
or php artisan queue:work
command. It neither processes the jobs saved in jobs table nor it gives any output on console.
However when I check jobs table, the attempts field of job keep incrementing. But job is not getting processed.
Also when I send mail directly using following code ie without adding it to queue. The mail got sent without any problem.
\Mail::send('email.new-friend-request', ['data'=>$friend_request], function($message) use (&$friend_request){
$message->to($friend_request->notifiable->email, $friend_request->notifiable->name)->from('info@example.com','ABC')->subject('New Friend Request');
});
Update
I tried sending email without any data and it also works without any issue. ie
\Mail::later(5, 'email.new-friend-request', [], function($message) use (&$friend_request){
$message->to($friend_request->notifiable->email, $friend_request->notifiable->name)->from('info@example.com','ABC')->subject('New Friend Request');
});
I got it, the problem was with Eloquent relations. When emails are qued then Eloquent model objects need to be serialized. Therefore once a model object is serialized then one can not access relations.
So I just tried eager loading model relations and also converted my model objects into an array using toArray()
method and then jobs started being processed.
That is before calling
\Mail::later(5, 'email.new-friend-request', ['data'=>$friend_request], function($message) use (&$friend_request){
$message->to($friend_request->notifiable->email, $friend_request->notifiable->name)->from('info@example.com','ABC')->subject('New Friend Request');
});
I eager loaded all the relations on $friend_request
object.
For Example:-
$friend_request = FriendRequest::with('notifiable')->find($request_id);
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.