Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
          ];
          }
        }
like image 487
Jonio Avatar asked Jan 19 '18 13:01

Jonio


1 Answers

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);
like image 174
Alexey Mezenin Avatar answered Nov 07 '22 09:11

Alexey Mezenin