Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Variable not passing into whereHas function - Laravel Eloquent

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

    }


}
like image 269
Nick Avatar asked Dec 23 '22 10:12

Nick


2 Answers

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();
like image 74
Laerte Avatar answered Jan 14 '23 01:01

Laerte


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

->whereHas('domains', function($q) use ($domain) {
    ...
});
like image 23
Jubin Avatar answered Jan 14 '23 01:01

Jubin