Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel event listeners undefined property error with ShouldQueue

I have an event setup within my application that sends out an activation email upon the user signing up. It works perfectly without the ShouldQueue interface. However, when I add implements ShouldQueue, I get undefined property error:

Undefined property: App\Events\User\UserCreated::$user

The code I am using is as follows:

<?php

namespace App\Listeners\User;

use App\Events\User\UserCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Repos\Email\EmailTemplateRepoInterface;
use App\Repos\User\UserRepoInterface;
use Request, Mail, DbView;

class UserCreatedEmail implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(EmailTemplateRepoInterface $template)
    {
        $this->template = $template;
    }

    /**
     * Handle the event.
     *
     * @param  UserCreated  $event
     * @return void
     */
    public function handle(UserCreated $event)
    {
        $user = $event->user;

        if($user)
        {
            if(!$user->status)
            {
                $user->activation_url = Request::root().'/activate/'.$user->activation_code;
                $template = $this->template->findTemplateByName('new_user_activation');
                $userArr = $user->toArray();
            }

            Mail::queue([], [], function ($message) use ($template, $userArr) 
            {
                $message->to($userArr['email'])
                    ->subject($template->subject)
                    ->setBody(DbView::make($template)->with($userArr)->render(), 'text/html');
            });
        }
    }
}

EDIT

Here is the UserCreated class as well:

<?php

namespace App\Events\User;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserCreated extends Event
{
    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($user, $row, $request)
    {
        $this->user = $user;
        $this->request = $request;
        $this->row = $row;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

Can anyone explain why this happens when I try to queue the email?

like image 855
V4n1ll4 Avatar asked Oct 30 '15 08:10

V4n1ll4


1 Answers

You need to explicitly define the property as public. I.e.

class UserCreated extends Event
{
    use SerializesModels;
    public $user;

...
like image 55
rdiz Avatar answered Nov 16 '22 07:11

rdiz