PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 7, 2022

[FIXED] How to create column aliases in a resource

 February 07, 2022     laravel, laravel-resource, resources     No comments   

Issue

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



Answered By - elmahdi bouzouggar
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing