Search code examples
phplaravel-4

Cannot pass variables to Mail::queue() message


Using Laravel 4.2, I am trying to queue mail messages using this code:

public function sendEmailNotices($type, $user, array $data = [])
{
    $type = strtoupper($type);
    $emails = [];

    if (Config::get("emailer.$type.email_others"))
        $emails = Config::get("emailer.$type.email_others");

    if (Config::get("emailer.$type.email_user"))
        $emails += [$user->email];

    if (!empty($emails)) {
        foreach ($emails as $email) {
            Mail::queue('emails.' . strtolower($type), array_merge((array)$data, ['user' => $user, 'is_user' => $email == $user->email]), function ($message) use ($email, $user, $type) {
                $message->to($email, $user->first_name . ' ' . $user->last_name)->subject(Config::get("emailer.$type.subject"));
            });
        }
    }
}

In the template I'm testing with I have:

<div>
    Welcome {{ $user->first_name }} {{ $user->last_name }} [{{ $user->email }}].
</div>

This always produces the error:

Trying to get property of non-object

I thought the User object just wasn't surviving the queue, so I tried changing it to pass 'first_name' as a variable. When I did I get the error:

Undefined variable: first_name

Why is nothing making it through to the template when queued? Works just fine when I do Mail::send() instead.


Solution

  • Mail::Send passes PHP variables as they are.

    Mail::Queue makes use of queues, which converts all your php variables into array notation.

    Into the rabbit hole, we go:

    Path : vendor\laravel\framework\src\Illuminate\Mail\Mailer.php Line 163

    public function queue($view, array $data, $callback, $queue = null)
    {
        $callback = $this->buildQueueCallable($callback);
    
        return $this->queue->push('mailer@handleQueuedMessage', compact('view', 'data', 'callback'), $queue);
    }