简介:我无法访问whereHas函数中的$domain变量(如下); Laravel返回以下错误:
“Undefined variable: domain”
我包括我的关系,因为我不确定雄辩的性质以及我如何调用此查询是否会导致问题.
我有一个中间件调用模型(组织)
组织模型有字段
subdomain
组织模型有
public function domains()
{
return $this->hasMany('App\Domain');
}
域模型(tablename域)具有字段
domain, org_id
还有功能
public function org()
{
return $this->belongsTo('App\Org');
}
我可以dd($domain);在此功能之前没有问题.但是,我得到了一个
“Undefined variable: domain”
对于下面whereHas函数内的查询参数.
为什么laravel看不到上面的变量?
namespace App\Http\Middleware;
use Closure;
class DomainLookup
{
protected $org;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$route = $request->route();
$domain = $route->parameter('domain');
$trimmed_domain = trim($domain, (config('app.domain')));
$this->org = \App\Org::where('subdomain',$trimmed_domain)
->whereHas('domains', function($q) {
$q->where('domain', $domain);
})
->get();
if ($this->org) {
return $next($request);
}
}
}
解决方法:
你需要在函数后调用use:
$this->org = \App\Org::where('subdomain',$trimmed_domain)
->whereHas('domains', function($q) use ($domain) {
$q->where('domain', $domain);
})
->get();
标签:php,laravel-5,eloquent
来源: https://codeday.me/bug/20190727/1550345.html