如何在 Laravel 5.5 中将数组作为 API 资源返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48342714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:16:21  来源:igfitidea点击:

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

phpjsonlaravelapi

提问by DavidInTheIn

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:

我在课堂上会写一些类似 ExampleResource 的东西:

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

}

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

如何转换值 $attribute 以执行此操作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
          ];
          }
        }

回答by Alexey Mezenin

Add constructor to the resource class:

向资源类添加构造函数:

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

Then in toArray():

然后在toArray()

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

And use it:

并使用它:

return new ExampleResource(Model::find($id), $attribute);

回答by dhinchliff

Resources are intended to be used to easily transform your models into JSON.

资源旨在用于轻松地将您的模型转换为 JSON。

Take a look at this example:

看看这个例子:

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

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

You just want to return an array of data so you should just return the array, it will be automatically turned into JSON:

你只想返回一个数据数组,所以你应该只返回数组,它会自动变成 JSON:

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

For more informations check the docs here

有关更多信息,请查看此处的文档