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?