array_key_exists() 错误/编辑供应商文件



我在 heroku 中部署的 laravel API 中遇到了一个小问题,它不知从何而来地发生在我身上,没有更新任何内容或进行任何相关更改,当我尝试使用任何雄辩的资源时,例如在执行时:

$brands = Brand::paginate(15);
return BrandResource::collection($brands);

我收到此错误:

array_key_exists((:不推荐在对象上使用 array_key_exists((。改用 isset(( 或 property_exists((

在 DelegatesToResource 中.php第 49 行

稍微调查一下,得到文件:DelegatesToResource.phpvendor,实际上它使用:

public function offsetExists($offset)
{
return array_key_exists($offset, $this->resource);
}

为了进行测试,我创建了一个新的Laravel项目,实际上它已经更正了该行,如下所示:

public function offsetExists($offset)
{
return isset($this->resource[$offset]);
}

如果在我的项目中有任何方法可以解决这个问题,我知道我不应该也不能更改vendor中的文件,所以我的问题是在这种情况下该怎么办?

我正在使用 Laravel 框架 5.6.39 和 PHP 7.2.18 (cli(

解决方案 1

将更新的代码添加到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  IlluminateHttpRequest  $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}

解决方案 2

如果要在多个资源中对数据进行分页,则最好扩展包含此更新函数的自定义类,而不是直接扩展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  IlluminateHttpRequest  $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}

最新更新