Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vipin93's avatar
Level 13

anyone know how print 1,2,3,4... in controller?

I try to save roll_no as 1, 2, 3,4... but its not increase the value only 0 inserting here is my controller

public function section_student_post(Request $r)
    {
        $this->validate($r,[

            'section'        =>      'required'
        ]);
        $students = Student::where('user_id',Auth::user()->owner->id)
                             ->where('course_id',1)
                             ->where('active',1)
                             ->select('id')
                             ->get();                           
         $datetime = Carbon::now();            
         foreach ($students as $key => $value)
       {    
             $i=0;        
        $data = [
                 'section_id' => $r->section [$key],
                 'roll_no'    => $i++,
                 'updated_at' => $datetime,
                 'created_at' => $datetime
          ];
          
          $value->studentacadmic()->create($data);
        
      }     

       flash()->success('Successfully students section assigned');
       return back();                            

    }

0 likes
2 replies
tomopongrac's avatar
Level 51

Try

public function section_student_post(Request $r)
    {
        $this->validate($r,[

            'section'        =>      'required'
        ]);
        $students = Student::where('user_id',Auth::user()->owner->id)
                             ->where('course_id',1)
                             ->where('active',1)
                             ->select('id')
                             ->get();                           
         $datetime = Carbon::now();   
             $i=1;           
         foreach ($students as $key => $value)
       {    
        $data = [
                 'section_id' => $r->section [$key],
                 'roll_no'    => $i++,
                 'updated_at' => $datetime,
                 'created_at' => $datetime
          ];
          
          $value->studentacadmic()->create($data);
        
      }     

       flash()->success('Successfully students section assigned');
       return back();                            

    }

tykus's avatar

What @tomi said... to explain further:

You have initialised the $i variable inside the foreach loop which means it is reset everytime the loop comes back around.

Secondly, the increment operation $i++ will increment the variable after it has been used. If you want to increment prior to use, then use ++$i

Please or to participate in this conversation.