Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel array_map get error "array_map(): Argument #2 should be an array"

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"

like image 733
monoy suronoy Avatar asked Nov 09 '15 08:11

monoy suronoy


1 Answers

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;
});
like image 57
Elie Faës Avatar answered Dec 04 '22 07:12

Elie Faës