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

vipin93's avatar
Level 13

How to assign student roll no?

I'm try to assign student roll no. using multifield form (foreach). problem is that suppose I have 25 student and I when I'm insert it automatically assign roll no by incremental one. now suppose after some time one more student come and when I try to assign roll no. its assign 1 again but I want to assign him 101 instead of 1

here is my controller method

$students = Student::where('user_id',Auth::user()->owner->id)
                             ->whereHas('courses',function($q) use ($course, $created_at){
                              $q->where('id',$course)
                                ->where('created_at',$created_at);
                             })->where('active',1)                           
                             ->doesntHave('studentacadmic')
                             ->select('id','course_id')
                             ->get();  
 $ i =1;
  foreach ($students as $key => $value)
       {    
         
        $data = [
                 'section_id' => $r->section [$key],
                 'roll_no'    => $i++, // it assign roll no 1,2,3.. but when I want try to assign again its again            start from 1 but I want add one value in roll no 
                 'course_id'  => $value->course_id,
                 'updated_at' => $datetime,
                 'created_at' => $datetime
          ];
          
          $value->studentacadmic()->create($data);
        
      }

thanks

0 likes
1 reply
vipin93's avatar
Level 13

here what I try

$roll_no = StudentAcadmic::whereHas('courses',function($q) use($course, $created_at){
                                     $q->where('id',$course)
                                     ->where('created_at',$created_at)
                                     ->where('user_id',Auth::user()->owner->id);
                                   })->orderBy('roll_no','desc')->select('roll_no')->first(); 
        if ($roll_no) {
          $roll_nos=$roll_no->roll_no; //here i fetch laat roll no if exist then print or 0
        }else{
          $roll_nos = 0;
        }
        
                                              
         $datetime = Carbon::now();   

               
         foreach ($students as $key => $value)
       {    
         
        $data = [
                 'section_id' => $r->section [$key],
                 'roll_no'    => $roll_nos += 1, //here I'm adding 1 but when section changed it adding 1 but when section change then it initialize from 1
                 'course_id'  => $value->course_id,
                 'updated_at' => $datetime,
                 'created_at' => $datetime
          ];
          
          $value->studentacadmic()->create($data);
        
      }  

now problem that here is course have many section so

Please or to participate in this conversation.