Skip to content
Advertisement

Why is this code showing $req variable undefined?

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;

class universityController extends Controller
{
    //

    public function getStudents(Request $req)
    {
        $students= DB::table('students')
        ->join('applicants', function ($join) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();
        return $students;
        // return $req->scholarshipid;
    }
}

Advertisement

Answer

As @lagbox mention, you are in an anonymous function and it can’t reach the outer scope so to fix this problem you need to use use like this

 public function getStudents(Request $req)
    {
        $students= DB::table('students')
        ->join('applicants', function ($join) use($req) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();
        return $students;
        // return $req->scholarshipid;
    }

for more info about anonymous function check the docs here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement