总结:我无法访问whereHas函数中的$ domain变量(如下); Laravel返回以下错误:
"未定义的变量:domain"
我包括我的关系,因为我不确定雄辩的性质以及我如何调用此查询是否会导致问题。
我有一个调用Model(Org)的中间件
组织模型有字段
子域
组织模型
public function domains()
{
return $this->hasMany('App\Domain');
}
域模型(表名域)包含字段
domain,org_id
还有功能
public function org()
{
return $this->belongsTo('App\Org');
}
我可以dd($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);
}
}
}
答案 0 :(得分:5)
您需要在功能后调用use
:
$this->org = \App\Org::where('subdomain',$trimmed_domain)
->whereHas('domains', function($q) use ($domain) {
$q->where('domain', $domain);
})
->get();
答案 1 :(得分:2)
您应该使用$domain
use
传递给关闭
->whereHas('domains', function($q) use ($domain) {
...
});