在 Laravel 9 中,报错:Call to undefined method Illuminate\\Http\\Resources\\MissingValue::isEmpty()

1、在 Laravel 9 中,报错:Call to undefined method Illuminate\\Http\\Resources\\MissingValue::isEmpty()。如图1

图1

2、查看代码实现

if ($this->whenLoaded('customTagsEnable')->isEmpty()) {
 return [];
}

3、打印 $this->whenLoaded(‘customTagsEnable’),其结果如下,分别为 资源在模型关联未被加载后、资源在模型关联被加载后 的结果

object(Illuminate\Http\Resources\MissingValue)#4330 (0) {
}

object(Illuminate\Database\Eloquent\Collection)#4177 (2) {
  ["items":protected]=>
  array(0) {
  }
  ["escapeWhenCastingToString":protected]=>
  bool(false)
}

4、重新实现如下,不再报错

use Illuminate\Http\Resources\MissingValue;

if ($this->whenLoaded('customTagsEnable') instanceof MissingValue) {
 return [];
}
永夜