我在 heroku 中部署的 laravel API 中有一个小问题,它从无处开始发生在我身上,没有更新任何东西或进行任何相关更改,当我尝试使用任何 Eloquent 资源时,它发生在我身上,例如做的时候:
$brands = Brand::paginate(15);
return BrandResource::collection($brands);
我收到这个错误:
array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead
in DelegatesToResource.php line 49
稍微调查一下,找到文件:vendor
中的 DelegatesToResource.php
,实际上它使用:
public function offsetExists($offset)
{
return array_key_exists($offset, $this->resource);
}
为了进行测试,我创建了一个新的 Laravel 项目,实际上它附带的那一行已经更正了,如下所示:
public function offsetExists($offset)
{
return isset($this->resource[$offset]);
}
如果在我的项目中有任何方法可以解决这个问题,我知道我不应该也不能更改 vendor
中的文件,所以我的问题是在这种情况下该怎么办?
我正在使用 Laravel Framework 5.6.39 和 PHP 7.2.18 (cli)
最佳答案
解决方案一
将更新后的代码添加到您的 BrandResource
中,使其看起来像这样:
class BrandResource extends JsonResource
{
/**
* Determine if the given attribute exists.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->resource[$offset]);
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
方案二
如果您在多个资源中对数据进行分页,那么最好扩展包含此更新函数的自定义类,而不是直接扩展 JsonResource
。
所以它看起来像这样:
class CustomResource extends JsonResource
{
/**
* Determine if the given attribute exists.
*
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->resource[$offset]);
}
}
并使用您的资源,例如:
class BrandResource extends CustomResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
关于php - array_key_exists() 错误/编辑供应商文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60212635/