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 🙁
3
Answers
use
$this->id
instead of onlyid
use $request->id insted id
This is more of a PHP error rather than a Laravel error. I’ll explain a few things.
Constants vs Local Variable:
Your function accepts a parameter which is named
$request
. The request parameter contains all of the information you pass to it. And I assume you pass an array or object which contains the keys/propertiesid
,technology
,area
,total_capacity
,working
,file_date
,created_at
, andupdated_at
.The problem with your code is, you are calling a constant in each of the array values you’re trying to populate. Constants in PHP are names or identifiers with fixed values. They’re like variables except for that once they are defined, they cannot be modified/changed.
Constants start with either a letter or an underscore in PHP and there are no
$
sign before a constant name.In your case, I think you are trying to access the property/key value from the
$request
object/array.You can access them by doing
$request->property_name_here
or$request['key_name_here']
and populate your array with values. Hope this helps.