I have this in a "Product" model to map the one to many relationship between a product and a barcode:
public function barcodes(){
return $this->hasMany('Barcode', 'productId', 'id')->select(['barcode', 'productId']);
}
Next, this code gives me not only the product, but also each barcode in an array of objects.
public function search(){
$results = Product::with('barcodes')->where('name', 'LIKE', 'theQueryString')->get();
return Response::json($return);
}
This is an example output:
{
"results": [
{
"id": 1,
"name": "Warehouse Box",
"created_at": "2034-12-14 06:57:52",
"updated_at": "2064-12-14 06:27:52",
"barcodes": [
{
"barcode": "0750028400400",
"productId": 1
},
{
"barcode": "123456789",
"productId": 1
}
]
}
]
}
Instead of "barcodes" returning an array of objects, I want "barcodes" just to be an array of values.
Said another way, I want to return the value of the "barcode" column in each barcode object instead of the object itself.
Here is what I want it to look like:
{
"results": [
{
"id": 1,
"name": "Warehouse Box",
"created_at": "2034-12-14 06:57:52",
"updated_at": "2064-12-14 06:27:52",
"barcodes": [
"0750028400400",
"123456789"
]
}
]
}
Is there a quick and smart way of doing this in Laravel using Eloquent?