0

This is the Laravel ProductController and Products has a many-to-many relationship with Tags.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $products = Product::with('tags')->latest()->get();
    return response()->json($products);
}

On the json response, if I map the products, product.tag is returning an array of objects.

[{"name": "shirt"}, {"name": "red"}]

Is there a way to get only the name property at the with('tags') at the controller, like:

["shirt", "red"]

Also I have been trying something like this:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $products = Product::with(['tags' => function ($query) {
        $result = $query->select(['name']);
        return $result->get();
    }])->latest()->get();
    return response()->json($products);
}

Its possible to filter the data inside tags function?

amimaro
  • 175
  • 3
  • 19

1 Answers1

0

You should probably use a Resource class to return just the items required in your API. This includes being able to process child relationships. See https://laravel.com/docs/6.x/eloquent-resources#generating-resources

Or, you can do it the way you tried with select but more like;

    $products = Product::with(['tags' => function ($query) {
        return $query->select(['name']);
    }])->latest()->get();
Thomas
  • 8,426
  • 1
  • 25
  • 49
Snapey
  • 3,604
  • 1
  • 21
  • 19