Laravel资源,当条件不是对象错误时

Lavavel resource, when condition non-object error

我尝试制作条件资源项,但在尝试获取 属性 'value' 的非对象

时出现错误


            'te' => $this->when($this->recup, $this->recup->test), // don't work
            'test' => $this->recup ? ($this->recup->test) : 'null', // works


 public function recup()
    {
        return $this->belongsTo(Animal::class);
    }

为什么 when 条件不起作用? 感谢

您需要像这样使用 optional() 方法:

'te' => $this->when($this->recup, optional($this->recup)->test)