Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is missing when using Laravel Mail::later

Tags:

queue

laravel

I have this code:

$data = ['user'=>User::find(1)];
Mail::later(5, 'email.template', $data, function($message){
  ...
})

And email.template have this:

print_r($user)

And when I received the email, the instance of $user is not User object. How could that happen? It is like the object is not referencing the right context. But when I use the Mail::send it is working fine. Little bit confused here.

like image 446
lukaserat Avatar asked Dec 04 '22 07:12

lukaserat


2 Answers

An Eloquent model is too big for a queue's job, which usually has a limit of 64kb.

I would advise you to use a regular queue job, pass it your user id, and fire off the email from there:

$user_id = 1;

Queue::later(5, function () use ($user_id) {
    $data = ['user' => User::find($user_id)];

    Mail::send('email.template', $data, function ($message) {
        // ......
    });
});
like image 144
Joseph Silber Avatar answered Dec 06 '22 20:12

Joseph Silber


I took a similar approach to the other two answerers, but I implemented it using a view creator. I was able to retrieve the variables from the view with $view->getData(), and from that I retrieved the Eloquent Model. You could use the following in conjunction with Mail::later or Mail::queue.

View::creator('email.template', function($view)
{
    $view_data = $view->getData();

    if (isset($view_data['user_id']))
    {
        $user_id = $view_data['user_id'];
        $view->with('user', User::find(user_id));
    }
});
like image 30
Andrew Avatar answered Dec 06 '22 20:12

Andrew