如何将数据库中的数据分配给 laravel 控制器中的数组?

How to assign data from database to array in laravel controller?

我想从数据库分配数据以将其存储在数组中。我没有收到任何错误,但只有最后一个值存储在数组中。

查询从数据库中获取数据

 $categories = Category::where('parent_id', '=', null)->where('created_by', '=', \Auth::user()->creatorId())->get();
      
$category = [];
            
           if(count($categories) > 0)
           {
                foreach ($categories as $category) {
                    
                    $category[$category->id] = [
                    'id' => $category->id,
                    'category_name' => $category->name,
                    'SubCategory' => $this->getSubcategoryByIdAction($category->id)
                      
                    ];
                        
                }
           }
           
      

您在 foreach 循环中覆盖了变量 $category。试试下面的代码:

<?php

$categories = Category::where('parent_id', '=', null)->where('created_by', '=', \Auth::user()->creatorId())->get();      
$category = [];
            
if(count($categories) > 0)
{
    foreach ($categories as $categoryItem) {
        
        $category[$categoryItem->id] = [
            'id' => $categoryItem->id,
            'category_name' => $categoryItem->name,
            'SubCategory' => $this->getSubcategoryByIdAction($categoryItem->id)  
        ];       
    }
}

var_dump($category);