Andrew
Andrew

Reputation: 866

How to list dynamic tables data in foreach loop

i have dynamic table and that table datas are listed one table i will try this way

$cat= DB::table('categories')->get(); //these is take table name 
 foreach($cat as $data){
 $res= DB::table($data->name)->get(); //query build
 }
return view('admin.company')->with('result',$res)->with('catg',$cat); // pass to view page

and i print data in view page but it list one table data only i print like this

@foreach($result as $datas)    
<td >  {{$datas->phone}} </td>
<td >  @foreach($catg as $cat) @if($cat->id==$datas->cat_id){{$cat->name}} @endif @endforeach </td>
<td >  {{$datas->discription}} </td>
@endforeach

how to list all tables data in one view any way? i am using laravel new version !

Upvotes: 1

Views: 423

Answers (2)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

You can do that more cleverly

$cat= DB::table('categories')->get(); //these is take table name
foreach($cat as $data){
    $res[$data->name] = DB::table($data->name)->get(); //query build
    // or 
    // $res[] = [
    //     'category' = $data,
    //     'data' => DB::table($data->name)->get()
    //]
}
return view('admin.company')->with('result',$res);

In view

@foreach($res as $tableName => $data)
    @foreach($data as $datas)
        <td >  {{$datas->phone}} </td>
        <td >  {{$tableName}} </td>
        <td >  {{$datas->discription}} </td>
    @endforeach
@foreach

Upvotes: 1

Jason
Jason

Reputation: 3040

This is failing to work because you are assigning to $res each time in your loop, so it will only be the last table information that shows.

Change the inner part of your loop to $res[] = DB::table($data->name)->get();

You will then need to create an outer loop in your view, as such

@foreach($res as $table)
  @foreach($table as $datas)    
  <td >  {{$datas->phone}} </td>
  <td >  @foreach($catg as $cat) @if($cat->id==$datas->cat_id){{$cat->name}} @endif 
  @endforeach </td>
  <td >  {{$datas->discription}} </td>
  @endforeach
@foreach

It may help also in your question to add why you are trying to what you are doing. I can see many other problems with your approach, but without knowing your data, it is hard to provide a better solution.

Upvotes: 1

Related Questions