Laravel Job无法识别对象属性

时间:2018-07-01 10:15:30

标签: laravel jobs laravel-events laravel-jobs

我正在将请求传递给职位类别,以发送电子邮件以获取联系表。问题是我无法直接访问该属性。

我在构造函数中将$ request设置为$this->request = $request;

handle()方法中,我这样做:

  

\ Log :: info('job-contact-request',['request'=> $ this-> request]);

日志弹出:

  

[2018-06-30 14:07:34] local.INFO:请求{“ request”:“ [对象](App \ Events \ ContactRequestValidated:{\” request \“:{\” client_name \“: \“ Daniel \”,\“ client_email \”:\“ email@email.com \”,\“ client_phone \”:\“ 1234567891 \”,\“ client_text \”:\“” \“ socket \”:null})“}

显示已设置client_email。但是当我尝试访问$this->request->client_email时,我得到了:

  

[2018-06-30 14:15:30]本地。错误:未定义的属性:App \ Events \ ContactRequestValidated :: $ client_email {“ exception”:“ [对象](ErrorException(code:0):未定义的属性:位于\ var / www / site / laravel / app / Jobs / SendContactRequestEmail.php:36的App \ Events \ ContactRequestValidated :: $ client_email   [stacktrace]

1 个答案:

答案 0 :(得分:0)

仅仅弄乱Laravel的事件/侦听器/工作,我不得不纠正一些问题。跨多个类拥有日志确实让我失望了。

在事件构造函数中,设置请求时必须使用all()方法。

$this->request = $request->all()以按属性名称正确访问数据。

// Event Constructor
public function __construct( ContactRequest $request )
    {
        $this->request = $request->all();
        // \Log::info( 'Event-Constructor', [ 'contact_request' => $this->request ] );
    }

事件向侦听器传递一个事件对象,该事件对象具有在事件构造函数中设置的数据作为事件对象的属性。必须通过事件对象访问数据。

// Listener
public function handle( ContactRequestValidated $event )
    {
        // \Log::info( 'listener', [ 'contact-event' => $event->request ] );

        dispatch( new SendContactRequestEmail( $event->request ));
    }

下一部分我不太确定为什么会发生这种情况,但是在工作中,请求已从对象更改为数组。

这是工作代码:

// Job Constructor
public function __construct( $request )
    {
        $this->request = $request; // Actually an array, not an object
    }

// Job handle
public function handle()
    {
        // \Log::info( 'job-contact-request', [ 'request' => $this->request ] );

        $email = new ConfirmContactRequest( $this->request );

        \Log::info( 'job-contact-request', [ 'email_html' => $email ] );

        // Note request has to be accessed by array notation rather than arrow method
        Mail::to( $this->request['client_email'] )->send( $email );
    }