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

I want (due to the project) to create an array in the class controller and pass it to the resource. In my controller class, consider this method:

public function getExample(){
  $attribute=array('otherInfo'=>'info');

  return new ExampleResource($attribute);
}

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

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

}

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

Please do not suggest me to insert information about the field in the model, this attribute can come only from the external, from the controller and does not apply to the model in the 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
          ];
          }
        }
+4
source share
2 answers

Add constructor to 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);
+1
source

JSON.

:

use App\User;
use App\Http\Resources\UserResource;

Route::get('/user', function () {
    return new UserResource(User::find(1));
});

, , JSON:

Route::get('/info', function () {
    return ['info' => 'info ...'];
});

0

Source: https://habr.com/ru/post/1692419/


All Articles