4
votes

Summary: I cannot access the $domain variable in the whereHas function (below); Laravel returns the following error:

"Undefined variable: domain"

I am including my relationships because I am not sure if the nature of eloquent and how I am trying to call this query is causing problems.


I have a middleware that is calling a Model (Org)

Org model has field

subdomain

Org model has

public function domains()
{
    return $this->hasMany('App\Domain');
}

Domain model (tablename domains) has fields

domain, org_id

Also has function

public function org()
{
    return $this->belongsTo('App\Org');
}

I can dd($domain); before this function with no problems. however, the I am getting a

"Undefined variable: domain"

for the query parameter inside the whereHas function below.

Why can't laravel see the variable set above?

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

    }


}
2
Replace function($q) with function($q,$domain)Hackerman
@Hackerman ... im still learning php, is that php behavior, or laravel magic? Re: function($q, $domain) .. vs .. function($q) use ($domain)Nick
The second is laravel magic...the first one is good ol' php.Hackerman

2 Answers

8
votes

You need to call use after function:

$this->org = \App\Org::where('subdomain',$trimmed_domain)
             ->whereHas('domains', function($q) use ($domain) {
                  $q->where('domain',  $domain);
              })
              ->get();
2
votes

You should pass the $domain to your closure with a use:

->whereHas('domains', function($q) use ($domain) {
    ...
});