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

1

7

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"

Auricle answered 9/11, 2015 at 8:57 Comment(4)
as per error $products should be an array, first convert your data into an array. also check passed variable is an array or notAlfano
how to check type data on laravel @Chetan AmetaAuricle
with basic php, you can var_dump the variable to analyze the variable. I think in your case $products is an objectAlfano
basically what is your desire result? can you explain bit more in your question. What output you want?Alfano
L
9

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;
});
Latvia answered 9/11, 2015 at 8:59 Comment(2)
echo $products->toArray() ... return empty for me @PeterPan666Auricle
echo do not display arrays, try with dd($products->toArray());Cartwheel

© 2022 - 2024 — McMap. All rights reserved.