Home > Enterprise >  How to loop foreach in laravel dynamically
How to loop foreach in laravel dynamically

Time:12-21

Am just learning Laravel and I have this logic were in I want to display array of total items based from user, to explain this further here is my database

user table

enter image description here

items table

enter image description here

this is my current code

public function display()
    {
       
            $users = User::where('type', 'Shop')->get();

            foreach($users as $user){
                $shop_id = $user['id'];
                $shop_name = $user['name'];
            }
            $total = Item::where('user_id', $shop_id)->sum('total');
            $shops =[
                ['Name' => $shop_name, 'total' => $total],
            ];

            return response()->json([
                "shops" =>$shops
            ], 200);

    }

and here is my sample output:

enter image description here

am only getting 1 object instead of 2 as I have two shops how to loop this dynamically.

thanks

CodePudding user response:

the $shops and $total variable is not in foreach loop that's because it returns only one row. and you must use $shops[] .

public function display()
    {
       
            $users = User::where('type', 'Shop')->get();

            foreach($users as $user){
                $shop_id = $user['id'];
                $shop_name = $user['name'];
                $total = Item::where('user_id', $shop_id)->sum('total');
                $shops[] =['Name' => $shop_name, 'total' => $total];
            }
           
            return response()->json([
                "shops" =>$shops
            ], 200);

    }

but the best and clean way is to use laravel relationship

in User model:

public function items()
{
return $this->hasMany(Item::class) ;
}

and display controller :

public function display()
 {
   $shops = User::where('type', 'Shop')->get()
            ->mapWithKeys(function($user){
               return ['name'=>$user->name ,
                       'total'=> $user->items->sum('total')
             ]});

  return response()->json(["shops" =>$shops], 200);

 }


CodePudding user response:

Do this

 $shops[] = ['Name' => $shop_name, 'total' => $total];

to push all the shops into one array.

You are currently overriding the hole array.

UPDATE: Also move the sql part into the foreach:

 foreach($users as $user){
     $shop_id = $user['id'];
     $shop_name = $user['name'];
     $total = Item::where('user_id', $shop_id)->sum('total');
     $shops[] =['Name' => $shop_name, 'total' => $total];
 }
  • Related