skip to Main Content

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


  1. use $this->id instead of only 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,
        ];
    
    Login or Signup to reply.
  2. use $request->id insted 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,
    ];
    
    Login or Signup to reply.
  3. 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/properties id, technology, area, total_capacity, working, file_date, created_at, and updated_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search