Skip to content
Advertisement

Loop through this multidimensional array and display as a list of items in Laravel Blade

I have the following array. I need to show first_names relevant to each team_name as a list.

array:7 [▼
  0 => array:6 [▶]
  1 => array:6 [▼
    "id" => 3
    "team_name" => "Backend"
    "description" => "Laravel is used"
    "created_at" => "2021-05-29 07:17:32"
    "updated_at" => "2021-05-31 02:16:50"
    "get_employees" => array:4 [▼
      0 => array:2 [▼
        "team_name" => "Backend"
        "first_name" => "Test1"
      ]
      1 => array:2 [▼
        "team_name" => "Backend"
        "first_name" => "Test2"
      ]
      2 => array:2 [▼
        "team_name" => "Backend"
        "first_name" => "Test3"
      ]
      3 => array:2 [▼
        "team_name" => "Backend"
        "first_name" => "Test4"
      ]
    ]
  ]
  2 => array:6 [▶]
  3 => array:6 [▶]
  4 => array:6 [▶]
  5 => array:6 [▶]
  6 => array:6 [▶]
]

As this way.

Team name:- Backend  

People:- Test1, Test2, Test3, Test4

Below is my code block in blade.php but it gives me the error ‘Trying to get property ‘team_name’ of non-object’. I tried several methods but was failed to create the loop.

@foreach($teamEmployees as $key => $teamArray){
   {{$key->team_name}}
        @foreach($teamArray as $team_Array)
            {{$teamArray['get_employees'][0]['first_name']}}
        @endforeach
}
@endforeach

This is my controller function if it is useful in any case.

public function teamsWithEmployee(){
        $teamEmployees=Teams::with(['get_employees'=>function($query){
            $query->select(['team_name','first_name']);
        }])->get()->toArray();
         dd ($teamEmployees);
       return view('teams-employee', compact('teamEmployees'));
     }

I am very new to PHP and Laravel. Previous questions on this type didn’t help me to solve this. Please help me in this. Thanks in advance

Advertisement

Answer

You have to access 'team_name' as arra key. And you can loop through the nested array via recursive templates:

@foreach($projects as $project)
    <div style="margin-left:10px;">
        Team name: {{ $project['team_name'] }}
        @if (array_key_exists('first_name', $project)
            {{ $project['first_name'] }}
        @end
        @if(array_key_exists('get_employees', $project) && count($project['get_employees']))
            @include('projects', [ 'projects' => $project['get_employees'] ])
        @endif
    </div>
@endforeach
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement