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"

4
  • as per error $products should be an array, first convert your data into an array. also check passed variable is an array or not Commented Nov 9, 2015 at 9:00
  • how to check type data on laravel @Chetan Ameta Commented Nov 9, 2015 at 9:05
  • with basic php, you can var_dump the variable to analyze the variable. I think in your case $products is an object Commented Nov 9, 2015 at 9:06
  • basically what is your desire result? can you explain bit more in your question. What output you want? Commented Nov 9, 2015 at 9:08

1 Answer 1

10

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

echo $products->toArray() ... return empty for me @PeterPan666
echo do not display arrays, try with dd($products->toArray());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.