1

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

{
   "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。

4

2 回答 2

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
    ];
}
于 2019-10-31T08:59:25.363 回答
0

短途;

邮政资源;

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->title,
        'type' => ucfirst($this->type)
    ];
}
于 2019-10-31T09:14:51.317 回答