[英]array_key_exists() error / edit a vendor file
我在 heroku 中部署的 laravel API 有一個小問題,它開始發生在我身上,沒有更新任何內容或進行任何相關更改,當我嘗試使用任何雄辯的資源時,它發生在我身上,例如在執行以下操作時:
$brands = Brand::paginate(15);
return BrandResource::collection($brands);
我收到此錯誤:
array_key_exists():不推薦在對象上使用 array_key_exists()。 改用 isset() 或 property_exists()
在 DelegatesToResource.php 第 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 框架 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 \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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.