Home > Back-end >  How to assign data from database to array in laravel controller?
How to assign data from database to array in laravel controller?

Time:11-11

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

CodePudding user response:

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);
  • Related