使用未定义的常量 id - 假定 'id'(这将在 PHP 的未来版本中引发错误)

Use of undefined constant id - assumed 'id' (this will throw an Error in a future version of PHP)

I have a jsonresource but it says undefined constant id

class DashboardGraphDataResource extends JsonResource
{

   public function toArray($request)
   {
    return [
        'id' => id,
        'technology' => technology,
        'area' => area,
        'totalCapacity' => total_capacity,
        'working' => working,
        'fileDate' => file_date,
        'created_at' => created_at,
        'updated_at' => updated_at,
    ];
}

}

Code inside my controller

return DashboardGraphDataResource::collection(DashboardGraphData::all());

But when I return DashboardGraphData::all() not putting it in DashboardGraphDataResource::collection(), the result is showing.

[{"id":1,"technology":"tech1","area":1,"total_capacity":"2936","working":936,"file_date":"2020-01-05","created_at":"2020-05-05 03:47:27","updated_at":"2020-05-05 03:47:27"}]

Is there something wrong with my query?Please Help Me :(

使用 $this->id 而不是仅 id

return [
        'id' => $this->id,
        'technology' => $this->technology,
        'area' => $this->area,
        'totalCapacity' => $this->total_capacity,
        'working' => $this->working,
        'fileDate' => $this->file_date,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];

使用 $request->id 而不是

return [
    'id' => $request->id,
    'technology' => $request->technology,
    'area' => $request->area,
    'totalCapacity' => $request->total_capacity,
    'working' => $request->working,
    'fileDate' => $request->file_date,
    'created_at' => $request->created_at,
    'updated_at' => $request->updated_at,
];

这更像是一个 PHP 错误,而不是 Laravel 错误。我会解释一些事情。

常量与局部变量:

您的函数接受一个名为 $request 的参数。请求参数包含您传递给它的所有信息。我假设您传递了一个包含 keys/properties idtechnologyareatotal_capacityworking、[=16 的数组或对象=]、created_atupdated_at.

您的代码存在的问题是,您在尝试填充的每个数组值中都调用了一个常量。 PHP 中的常量是具有固定值的名称或标识符。它们就像变量,只是一旦定义,它们就不能是 modified/changed.

在 PHP 中常量以字母或下划线开头,常量名称前没有 $ 符号。

在您的情况下,我认为您正在尝试从 $request object/array.

访问 property/key 值

您可以通过 $request->property_name_here$request['key_name_here'] 访问它们并用值填充您的数组。希望这会有所帮助。