Search code examples
phplaravelmultidimensional-arrayforeachlaravel-7

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


I want to assign data from database to store it in array. I am not getting any error, but only last value getting stored in array.

query to get data from database

 $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)
                      
                    ];
                        
                }
           }
           
      

Solution

  • You overwrite the variable $category in your foreach loop. Try the following code:

    <?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);