【问题标题】:How to return an array as an API resource in laravel 5.5如何在 laravel 5.5 中将数组作为 API 资源返回
【发布时间】:2018-06-28 18:57:29
【问题描述】:

我想(出于项目原因)在类控制器中创建一个数组并将其传递给资源。 在我的控制器类中考虑这个方法:

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

  return new ExampleResource($attribute);
}

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

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

}

如何转换值 $attribute 以执行此操作return new ExampleResource($attribute);

请不要建议我在模型中插入字段信息,该属性只能来自外部,来自控制器,不属于数据库中的模型。

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
          ];
          }
        }

【问题讨论】:

  • 您的问题令人困惑。您想要return new ExampleResource($attribute); 的数组吗?听起来您几乎是在尝试创建模型工厂?

标签: php json laravel api


【解决方案1】:

给资源类添加构造函数:

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

然后在toArray():

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

并使用它:

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

【讨论】:

  • @user8958651 我在发布之前已经测试过这段代码,我也使用过数组。请告诉我究竟是哪一行引发了错误?另外,请显示您现在尝试使用的确切代码。
  • 正如您在编辑文件中看到的,错误在构造函数中:$this->$info= $info;
  • @user8958651 将$this->$info = $info; 更改为$this->info = $info; 并在toArray() 中执行相同操作。我刚刚复制粘贴了$attribute,并没有删除$ 符号。
  • 将 $this->info=$info 放入 costructor,并将 'info'=>$this->info 放入 toArray ,执行返回错误“尝试获取非对象的属性”关于 public function __get($key) { return $this->resource->{$key} 的方法; } 在库 Http\Resources\DelegatesToResource.php
  • @user8958651 请将问题中的代码更新为当前代码。
【解决方案2】:

资源旨在用于轻松地将您的模型转换为 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 ...'];
});

有关更多信息,请查看文档here

【讨论】:

  • 如果我想得到数组而不先返回怎么办?
猜你喜欢
  • 2018-08-08
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 2019-03-03
  • 2021-10-15
  • 2018-07-01
  • 2020-10-06
  • 2020-08-10
相关资源
最近更新 更多