【问题标题】:array_key_exists() error / edit a vendor filearray_key_exists() 错误/编辑供应商文件
【发布时间】:2020-05-29 10:40:46
【问题描述】:

我在 heroku 中部署的 laravel API 有一个小问题,它从无处开始发生在我身上,没有更新任何内容或进行任何相关更改,当我尝试使用任何 eloquent 资源时,它就会发生在我身上,例如做的时候:

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

我得到这个错误:

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

在 DelegatesToResource.php 第 49 行

调查一下,找到文件:DelegatesToResource.php in vendor,实际上它使用:

 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)

【问题讨论】:

  • 你知道如何改变它,所以这样做。如果您不能或不会更改它,请在您拥有它的任何地方调整错误报告E_ALL & ~E_DEPRECATED
  • 尝试升级你的 laravel。你的版本是 1-2 岁...
  • 还有一种方法,就是下载包到本地,改一下。在您的 composer.json 中,您必须在本地引用包。
  • 我检查了 laravel 源代码的 github repo 中的一些最后提交,他们已经解决了这个问题:public function offsetExists($offset) ` {` ` - return array_key_exists($offset, $this->resource);` ` + return isset($this->resource[$offset]);` } `

标签: php laravel eloquent vendor


【解决方案1】:

解决方案 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  \Illuminate\Http\Request  $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  \Illuminate\Http\Request  $request
         * @return array
         */
        public function toArray($request)
        {
            return parent::toArray($request);
        }
    }

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多