1

My Post Model has the following format:

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

Here is my controller method:

public function show($id) {

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

      return $transformedPost;
}

Here is how my PostResource looks:

public function toArray($request)
{

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

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

So in show/1 response, I should get:

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

Instead, I am getting:

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

So my PostResource is clearly not working as expected. Key "title" is not being substituted by key "name".


What am I missing here? I know there could be possible duplication of this post but the solutions in other questions seem not working for me.

I am using Laravel 6.x.

Scarecrow
  • 66
  • 6

2 Answers2

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

Your PostResource should now be

public function toArray($request)
{

    return [
        'id' => $this->id,
        'name' => $this->title,
        'type' => $this->type
    ];
}
mamaye
  • 1,009
  • 1
  • 8
  • 17
  • Not exactly what the problem is. I am not getting the PostResource to work here at all. See, "Title" key is not being substituted with "Name" key. So if I return $response->name, I am getting error. – Scarecrow Nov 04 '19 at 05:23
0

Short way;

PostResource;

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->title,
        'type' => ucfirst($this->type)
    ];
}
Yusuf Onur Sari
  • 394
  • 2
  • 9
  • Not exactly what the problem is. I am not getting the PostResource to work here at all. See, "Title" key is not being substituted with "Name" key. So if I return $response->name, I am getting error. – Scarecrow Nov 04 '19 at 05:23