【问题标题】:Laravel API Resource doesn't work in Controller MethodLaravel API 资源在控制器方法中不起作用
【发布时间】:2019-10-31 08:53:57
【问题描述】:

我的帖子模型具有以下格式:

{
   "id": 1,
   "title": "Post Title",
   "type: "sample"
}

这是我的控制器方法:

public function show($id) {

      $post = App\Post::find($id);
      $transformedPost = new PostResource($post);

      return $transformedPost;
}

这是我的 PostResource 的外观:

public function toArray($request)
{

    return [
        'id' => $this->id,
        'name' => $this->title,
        'type' => $this->convertType($this->type),
    ];
}

public function convertType($type)
{
    return ucfirst($type);
}

所以在 show/1 响应中,我应该得到:

{
   "id": 1,
   "name": "Post Title",
   "type: "Sample"
}

相反,我得到:

{
   "id": 1,
   "title": "Post Title",
   "type: "sample"
}

所以我的 PostResource 显然没有按预期工作。键“title”没有被键“name”替换。


我在这里缺少什么?我知道这篇文章可能会重复,但其他问题的解决方案似乎对我不起作用。

我正在使用 Laravel 6.x。

【问题讨论】:

    标签: php laravel jsonapi-resources


    【解决方案1】:
    //I'm trusting you want to use an Accessor.
    
    //In your Post Model, try something like this
    
    public function getTypeAttribute($value)
        {
          return ucfirst($value);
        }
    

    你的 PostResource 现在应该是

    public function toArray($request)
    {
    
        return [
            'id' => $this->id,
            'name' => $this->title,
            'type' => $this->type
        ];
    }
    

    【讨论】:

    • 不完全是问题所在。我根本没有让 PostResource 在这里工作。请参阅,“标题”键没有被“名称”键替换。所以如果我返回 $response->name,我会得到错误。
    【解决方案2】:

    短途;

    发布资源;

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->title,
            'type' => ucfirst($this->type)
        ];
    }
    

    【讨论】:

    • 不完全是问题所在。我根本没有让 PostResource 在这里工作。请参阅,“标题”键没有被“名称”键替换。所以如果我返回 $response->name,我会得到错误。
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 2017-03-14
    • 2022-12-20
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2020-01-26
    • 2014-12-19
    相关资源
    最近更新 更多