How to return an array as an API resource in laravel 5.5

12,659

Add constructor to the resource class:

public function __construct($resource, $attribute)
{
    $this->resource = $resource;
    $this->attribute = $attribute;
}

Then in toArray():

return [
    'info' => $this->attribute,
    'created' => $this->created_at
];

And use it:

return new ExampleResource(Model::find($id), $attribute);
Share:
12,659
Jonio
Author by

Jonio

Updated on August 09, 2022

Comments

  • Jonio
    Jonio over 1 year

    I want (for project reason), to create an array in a class controller and pass it to a resource. Consider in my controller class this method:

    public function getExample(){
      $attribute=array('otherInfo'=>'info');
    
      return new ExampleResource($attribute);
    }
    

    and I in my class I would write sominthing like ExampleResource with:

    public function toArray($request){
    return[
    'info' => $this->info
    ];
    
    }
    

    How I can convert the value $attribute to perform this operation return new ExampleResource($attribute); ?

    Please do not suggest me to insert the field info in the model, this attribute can came from only from the external, from the controller and do not belong to the model in database.

    class ExampleResource extends Resource
    {
        private $info;
        /**
         * 
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
         public function __construct($info)
         {
             $this->$info = $info;
         }
    
    
        public function toArray($request)
        {
            return[
              'info'=>$this->$info,
              'id' => $this->id
              ];
              }
            }