0

I am trying to make a conditional where, inside a select statement. It is throwing undefined variable 'class_id'. What is going wrong here. The variable class_id got some value but is throwing 'Undefined variable: class_id'.

$class_id = isset($searchData[1]) ? $searchData[1] : '';

\Log::info($class_id);
    
$students = \User::where('role', 'student')
    ->where('fullName', 'like', '%'.$student_name.'%')
    ->orWhere('username', 'like', '%'.$student_name.'%')
    ->orWhere('email', 'like','%'.$student_name.'%')
    ->when($class_id != '',
        function ($q) {
            return $q->where('studentClass', '=', $class_id);
        })
    ->get();
mrhn
  • 17,961
  • 4
  • 27
  • 46
Malaiselvan
  • 1,153
  • 1
  • 16
  • 42

1 Answers1

1

You are using the wrong syntax for when(). You are using it in the perfect scenario, and you can omit initializing the variable above.

Laravel 5.2 -> 5.5

$class_id = isset($searchData[1]) ? $searchData[1] : '';

$students = \User::where('role','student')
    ->where('fullName','like','%'.$student_name.'%')
    ->orWhere('username','like','%'.$student_name.'%')
    ->orWhere('email','like','%'.$student_name.'%')
    ->when($class_id, function ($query) use ($class_id) {
        return $query->where('studentClass','=', $class_id);
    })->get();

Laravel 5.6+

$students = \User::where('role','student')
    ->where('fullName','like','%'.$student_name.'%')
    ->orWhere('username','like','%'.$student_name.'%')
    ->orWhere('email','like','%'.$student_name.'%')
    ->when($searchData[1], function ($query, $class_id) {
        return $query->where('studentClass','=', $class_id);
    })->get();

Kurt Friars
  • 3,625
  • 2
  • 16
  • 29