I'm new on laravel. Why I'm always get error:
array_map(): Argument #2 should be an array ?
whereas I'm assigning parameter array on this method?
this is my example code :
$products = Category::find(1)->products;
note : 1 category has many products
this is the array from query :
[{
"id": "1",
"name": "action figure",
"created_at": "2015-11-09 05:51:25",
"updated_at": "2015-11-09 05:51:25"
}, {
"id": "2",
"name": "manga",
"created_at": "2015-11-09 05:51:25",
"updated_at": "2015-11-09 05:51:25"
}]
when I'm trying the following code:
$results = array_map( function($prod) {
return $prod.name;
}, $products);
and I get the error like below:
"array_map(): Argument #2 should be an array"
You should write
$results = array_map(function ($prod) {
return $prod->name;
}, $products->toArray());
Because $products
is a Collection and not an array.
If you just want to have a list of product name use the pluck
method
$results = $products->pluck('name')
In newer version of Laravel you should use $products->all();
instead of toArray
because in the case of an Eloquent collection, toArray
will try to convert your models to array too. all
will just return an array of your models as is.
That being said, since you are on a Collection you can also use the map
method on it like so (which is exactly the same as using pluck
in your case)
$products->map(function ($product) {
return $product->name;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With