You need to enable JavaScript to run this app. Laravel控制器传变量到队列Job报Undefined property是什么原因?
优惠活动
大模型
产品
解决方案
定价
更多

Laravel控制器传变量到队列Job报Undefined property是什么原因?

错误原因

你的RegisterConfirmationJob类未提前声明$user成员属性,直接在构造方法中对$this->user赋值,PHP无法识别未定义的类属性,因此抛出了该报错。

修复方案

在类内部新增$user属性声明即可,修改后的完整代码如下:

<?php

namespace App\Jobs;

use App\Mail\RegisterConfirmation;
use App\User;
use Illuminate\Support\Facades\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RegisterConfirmationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    // 新增$user属性声明,可根据需求设置为public/protected/private
    public User $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function handle()
    {
        Mail::to($this->user)->send(new RegisterConfirmation($this->user));
    }
}

如果你的项目使用的PHP版本低于7.4,不支持属性类型声明,直接写public $user;即可。

优化建议

Laravel的邮件门面原生支持队列能力,无需单独封装Job类即可实现队列发送,你可以直接在控制器中使用如下写法,简化代码逻辑:

Mail::to($user)->queue(new RegisterConfirmation($user));

内容的提问来源于stack exchange,提问作者Felix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 18:57:01