Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nova Relatable Filtering - how to filter users whose company_id matches locations company_id

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

}
like image 836
C. Gill Avatar asked Nov 06 '18 21:11

C. Gill


1 Answers

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);
}
like image 114
Saumini Navaratnam Avatar answered Nov 15 '22 05:11

Saumini Navaratnam