spqa
868
1
Laravel

Hidden field in API Resource using Conditional Attributes?

Posted 1 year ago by spqa

Now, I'm trying to building API Resource and I wanna hide some kind of data.

For example, I want to hide attribute 'description' only in MangaCollection. I mean I just only wanna hide this attribute in Collection, not Resource. Because Collection be called from Resource but I don't want to hide it in Resource.

MangaResource.php

class MangaResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'status' => $this->status,
            'view' => $this->name,
            'slug' => $this->slug,
            'avatar' => $this->avatar,
            'description' => $this->description,
            'created_at' => (string) $this->created_at,
            'updated_at' => (string) $this->updated_at,
            'authors' => AuthorResource::collection($this->authors),
            'categories' => CategoryResource::collection($this->categories)
        ];
    }
}

MangaCollection.php

class MangaCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  Request $request
     * @return AnonymousResourceCollection
     */
    public function toArray($request)
    {
        return MangaResource::collection($this->collection);
    }
}

MangaController.php

class MangaController extends Controller
{
    /**
     * Display a collection of the mangas.
     *
     * @return MangaCollection
     */
    public function index()
    {
        return new MangaCollection(Manga::paginate(10));
    }

    /**
     * Display the specified manga.
     *
     * @param Manga $manga
     * @return MangaResource
     */
    public function show(Manga $manga)
    {
        return new MangaResource($manga);
    }
}

Could consider using Conditional Attributes to solve this problem, anyone can help me, please ?

Please sign in or create an account to participate in this conversation.