Why is this code showing $req variable undefined?

Tags: , , , ,



<?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;
    }
}

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



Source: stackoverflow