4

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

    }


}
3
  • Replace function($q) with function($q,$domain) Commented Feb 5, 2018 at 19:58
  • @Hackerman ... im still learning php, is that php behavior, or laravel magic? Re: function($q, $domain) .. vs .. function($q) use ($domain) Commented Mar 1, 2018 at 18:49
  • The second is laravel magic...the first one is good ol' php. Commented Mar 1, 2018 at 19:10

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.