laravelresourceslaravel-resource

How to create column aliases in a resource


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\""}

Solution

  • you can return array of custom fields like this

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

    see documentation