Search code examples
phplaravelcontrollerinner-joinquery-builder

Why is this code showing $req variable undefined?


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

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

Solution

  • 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