Laravel Advanced how to pass variable into nested where function?

Table of Contents
When using a variable inside a Closure scope, you must use the “use” keyword to pass the variable into the Closure:

foreach ($user->locations as $location) {
    $r = TableName::where('id', '<>', $this->id)
        ->where(function ($q) use ($code) { // SEE HERE
            $q->where('name', $code)
              ->orWhere('alias', $code);
        })
        ->get();
}
  



If you have an array variable like $requestParam['name'], you need to define it before the query statement:

$name = $requestParam['name'];
$lastRecordResult = YrModel::where('type', self::table)
    ->where(function ($q) use ($name) {
        $q->where('name', $name)
          ->orWhere('alias', $name);
    })
    ->where('t_id', $requestParam['t_id'])
    ->where('v_id', $requestParam['v_id'])
    ->count();
  

Related posts