0

I am creating an API using Laravel.

I created a table called transaction. I also created a resource called transactionresource.

I want to change the id column to be the key column in the API, and I don't want id to show in the API; instead key should show.

My code

class TransactionResource extends JsonResource
{
  
    public function toArray($request)
    {
        $array = parent::toArray($request);

        // set the new key with data
        $array['key'] = $array['id'];

        // unset the old key
        unset($array['id']);
        
        return $array;
    }
}

I am getting this error

{"success":false,"message":"Undefined array key \"id\""}
etranz
  • 891
  • 2
  • 10
  • 29

1 Answers1

2

you can return array of custom fields like this

public function toArray($request){
   return [
    'key' => $this->id,
    ...
];}

see documentation