mafortis
mafortis

Reputation: 7138

Laravel resource and related tables

I am getting my posts with resources and with this posts I also collect their categories but the categories come with full data, I need to limit returned data of categories,

Sample

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'url' => $this->slug,
            'body' => $this->body,
            'user' => $this->user,
            'categories' => $this->categories,
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
        ];
    }
}

Code above return data like:

0   
id  75
title   "Fpost title"
url "post-slug"
body    "post_body"
user    {…}
categories  
 0  
  id    1
  title "xx"
  slug  "xx"
  photo "xx"
  meta_tags "xx"
  meta_description  "xx"
  status    "xx"
  created_at    "xx"
  updated_at    "xx"
  pivot {…}
 1  
  id    9
  title "xx"
  slug  "xx"
  photo "xx"
  meta_tags "xx"
  meta_description  "xx"
  status    "xx"
  created_at    "xx"
  updated_at    "xx"
  pivot {…}
created_at  "xx"
updated_at  "xx"

Form categories all I need is Title & Slug.

Question

How do I limit categories data to title and slug only?

Upvotes: 1

Views: 217

Answers (1)

Sandeep Sudhakaran
Sandeep Sudhakaran

Reputation: 1092

Try the below code, I made some changes in your code,

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
   public function toArray($request)
   {
      return [
        'id' => $this->id,
        'title' => $this->title,
        'url' => $this->slug,
        'body' => $this->body,
        'user' => $this->user,
        'categories' => CategoryResource::collection($this->whenLoaded('categories')),
        'created_at' => (string) $this->created_at,
        'updated_at' => (string) $this->updated_at,
      ];
   }
}

Note: add your CategoryResource depends on your relation.

and create a resource for Category CategoryResource

class CategoryResource extends JsonResource
{     
  public function toArray($request)
   {
      return [
        'title' => $this->title,
        'url' => $this->slug,
      ];
   }
}

Upvotes: 3

Related Questions