在laravel 5.2中的控制器中的Foreach

时间:2016-07-28 11:43:28

标签: php foreach laravel-5

我想在selecct查询中的foreach中选择$ selected_student应该选择所有具有所有受尊重的student_id的列,然后显示数据表(它没有做同样的并且给出错误)。

我正在使用yajra datatable。

控制器

public function anyData(Request $request)
{
    $selected_batch_value = Session::get('batch_selection');

    $select_student = DB::table('student_batch')
      ->select('student_id')
      ->where('batch_id', '=', $selected_batch_value)
      ->get();

    if($selected_batch_value != 0) {  
        foreach($select_student as $select_student) {         
            $student[] = student::select('student_id', 'first_name','middle_name','last_name', \DB::raw('CONCAT(first_name, " ",middle_name, " " ,last_name) AS full_name'), 'mobile_num', 'email','address_line1','address_line2','state','city','pincode',\DB::raw('CONCAT(address_line1, "<br>",address_line2, "<br> " ,state, "<br>",city,"<br>",pincode) AS address'))
            ->where('student_id', '=', $select_student->id)
            ->get();                  
        }

        return Datatables::of($student)->make(true);
    } else {
        $student = student::select('student_id', 'first_name','middle_name','last_name', \DB::raw('CONCAT(first_name, " ",middle_name, " " ,last_name) AS full_name'), 'mobile_num', 'email','address_line1','address_line2','state','city','pincode',\DB::raw('CONCAT(address_line1, "<br>",address_line2, "<br> " ,state, "<br>",city,"<br>",pincode) AS address'));

        return Datatables::of($student)->make(true);
    }      
}

1 个答案:

答案 0 :(得分:1)

错误发生在foreach循环中,

这是结构或foreach循环,

foreach ($variable as $key => $value){
 # code...
}

在您的情况下,$variable$value相同,都是$select_student。将其改为,

foreach($select_student as $value){
$student[] = student::select('student_id', 'first_name','middle_name','last_name', \DB::raw('CONCAT(first_name, " ",middle_name, " " ,last_name) AS full_name'), 'mobile_num', 'email','address_line1','address_line2','state','city','pincode',\DB::raw('CONCAT(address_line1, "<br>",address_line2, "<br> " ,state, "<br>",city,"<br>",pincode) AS address'))
      ->where('student_id', '=', $value->id)
      ->get();
}