我需要在laravel中改变回报。 对象到数组{}到[](错误尝试diff'[对象对象])

I need change return object to array in laravel api.
anyone guide? I am getting error, cant figure out why??

change {} to this []

ERROR Error: "Error trying to diff '[object Object]'. Only arrays and iterables are allowed (API Laravel and front-end angular 7)

my code api Laravel

public function show($id)
    {

        $arCategoria = \App\Favorito::join('categoria', 'categoria.cd_categoria', '=', 'link.cd_categoria')
        ->select('*')
        ->where('categoria.cd_categoria_pai',$id)
        ->where('link.cd_usuario',$this->token['cd_usuario'])
        ->where('link.bo_ativo',true)
            ->get();
        return (array)$this->processarCategoria($arCategoria);
    }
    public function processarCategoria($arCategoria){
        $ar = array();
        $cont = 0;
        foreach($arCategoria as $key => $value){
            $ar[$value['no_categoria'].'_'.$value['cd_categoria']][] =  (array)array(
                'no_link'=>$value['no_link'],
                'cd_link'=>$value['cd_link'],
                'vl_link'=>$value['vl_link'],
                'bo_ativo'=>$value['bo_ativo'],
                'link'=>$value['link']
            );
           $cont++;
        }

        return (array)$ar;
    }

my return of laravel api

{
    "Documentation_3": [
        {
            "no_link": "stackoverflow",
            "cd_link": 5,
            "vl_link": null,
            "bo_ativo": 1,
            "link": "https://stackoverflow.com"
        },
        {
            "no_link": "Adventures of Time",
            "link": "http://adventuresoftime.com.br"
        }
    ],
    "Things to buy_5": [
        {
            "no_link": "Games",
            "link": "Games.com.br"
        }
    ]
}

If dd($this->processarCategoria($arCategoria->toArray())) is a plain PHP array, which means it works.

Btw, I think your original code works,too, maybe you dd((array) $this->processarCategoria($arCategoria)) and check.


According to PHP.net, (array)$scalarValue is exactly the same as array($scalarValue)

According to Laravel document, The toArray() method converts the collection into a plain PHP array.


And the reason why the array become a JSON after return, as if someone using the json_encode PHP function, is because:

Laravel automatically convert the array into a JSON response, in addition to returning strings from your routes and controllers. Laravel document

I.e., laravel convert array to JSON, so it may show on the screen.

Route::get('/', function () {
    //return is the same as dd()
    //dd(json_encode([1=>'a', 2=>'b', 3=>'c']));
    return [1=>'a', 2=>'b', 3=>'c'];
});