Home > Software design >  Get Data from foreach loop in controller
Get Data from foreach loop in controller

Time:11-28

I have one country model. Which is in one to many relation. One student has many countries. One student can go to many countries.

In Another model named division has no relation to Student. I stored country name in the division and has many data under country with one to many relation with some more model.

I want to get the country name(most cases there is more than one) under one student and with that country names I want to go to division and so on. I might not be able to explain clearly But you will understand with the code.

$countries = DB::table('countries')->where('student_id', '=', $id)->get(); //getting countries
foreach($countries as $country){
   $dis = DB::table('division')->where('country_name', '=', $country->country_name)->get();
}
dd($dis);

I tried

$dis = '';
foreach($countries as $key => $value){
   $dis = DB::table('divisions')->where('country_name', '=', $value->country_name)->get();
}

Where I am getting only one country info. And I tried

$dis = '';
foreach($countries as $key => $value){
  $dis .= $key .':' . $value->country_name . ',';
}

Here I am getting the both country but How to implement this to together! How can I append the data to $dis. I tried many-to-many. But still I am new to laravel so I am stuck after pivot table. I prefer using this more than many-to-many. Thank you in advance.

CodePudding user response:

Hopefully you can achieve your requirement with this way -

  $dis = array();
       foreach($countries as $key => $value){
           $dis[$key] = DB::table('divisions')->where('country_name', '=', $value->country_name)->get();
        }
dd($dis);

CodePudding user response:

Try array instead of singular variable:

$dis = []; // empty array
foreach($countries as $key => $value){
    // push into array
   $dis[] = DB::table('divisions')->where('country_name', '=', $value->country_name)->get();
}

this would be more cleaner and efficient

  • Related