PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] How to assign data from database to array in laravel controller?

 January 22, 2022     foreach, laravel, laravel-7, multidimensional-array, php     No comments   

Issue

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


Answered By - Douma
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing