I have a many to many relationship between users and locations. I want to filter my "attach user" select list to only show users whose company_id
matches the company_id
of the location I am currently on. I have created a static function called relatableUsers
which adds a "where" clause to the query.
public static function relatableUsers(NovaRequest $request, $query)
{
return $query->where('company_id', ???);
}
How do I pull the current location's company_id
into this where query? If I hard code a company_id
like below the filter works, so I know this is possible.
public static function relatableUsers(NovaRequest $request, $query)
{
return $query->where('company_id', 'FA624E60-DD37-11E8-A540-C3C0A709EE15');
}
The record information is not stored in the $request
or the $query
.
EDIT - adding relationships
User model:
public function company()
{
return $this->belongsTo(Company::class);
}
public function locations()
{
return $this->belongstoMany(Location::class);
}
Location model:
public function company()
{
return $this->belongsTo(Company::class);
}
public function users()
{
return $this->belongstoMany(User::class);
}
Company model relationships:
public function users()
{
return $this->hasMany(User::class);
}
public function location()
{
return $this->hasMany(Location::class);
}
You can retrieve the target Location
from the request like below.
public static function relatableUsers(NovaRequest $request, $query)
{
$location = $request->findResourceOrFail(); // Retrieve the location instance
return $query->where('company_id', $location->company_id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With