Muhammad Atallah
Muhammad Atallah

Reputation: 976

foreach in laravel controller

I try to loop over foreach in my Registration Controller as the following

      $subjectStartID  = Input::get('substID');

      $subjectStart = SubjectStart::find($subjectStartID);

    //To get division_ids by the relationships using SubjectStartID
       $divisionIDs =$subjectStart->teachersubject->subject->divisions ;

    // loop over $divisionIDs to get div_ids 
    foreach ($divisionID as $div) 
        {
          $div->id ;  
        }

       return var_dump($div->id);

OR

      return var_dump([$div->id]);

The isuue that the result of the loop get the last id only ,
for example if the div_ids (1,2) the result is (2)

i need foreach to get the div_ids to use it in the following joinQuery

 $check = Registration::join('student', 'student.id' ,'=' , 'registration.student_id')
                      ->join('division', 'division.id' ,'=' , 'student.division_id')
                      ->where('student.id' , $registerID->student_id)
                      ->whereIn('student.division_id',[$div->id])->get();

Any Suggestions ?

Upvotes: 0

Views: 14701

Answers (1)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13948

I can't say about laravel, but from a php standpoint, you should use a container array to store all the ids returned in the foreach loop.

imho, so your code should look like the following...

 $subjectStartID  = Input::get('substID');

  $subjectStart = SubjectStart::find($subjectStartID);

//To get division_ids by the relationships using SubjectStartID
   $divisionIDs =$subjectStart->teachersubject->subject->divisions ;



$studivs = array();
// loop over $divisionIDs to get div_ids 
foreach ($divisionID as $div) 
    {
     $studivs[] = $div->id ;  
    }

So now the variable $studivs has all the ids that you need.

Upvotes: 4

Related Questions