Pluck on Laravel Collection

  laravel, php

I am creating an API with Laravel 8.

I want to return a Model Tool Collection

ToolCollection.php

public function toArray ($ request)
    {
        return [
            'status' => 200,
            'message' => null,
            'data' => $ this-> collection
        ];
    }

This is the format I have at the moment:

{
    ...,
    "data": {
        ...,
        "tags": [
            {"title": "node"},
            {"title": "react"},
            {"title": "bootstrap"}
        ]
    }

This is the format I want:

{
    ...,
    "data": {
        ...,
        "tags": [
            "node",
            "react",
            "bootstrap"
        ]
    }

Tags is a many to many relationship always included in the model.
In ToolResource I got what I wanted using the pluck function, but as this is a Collection I don’t know how to apply this to all elements.

Source: Laravel

Leave a Reply