Laravel API Resource doesn't work in Controller Method

1.5k Views Asked by At

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.

2

There are 2 best solutions below

1
On
//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
    ];
}
1
On

Short way;

PostResource;

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