使用数据透视表过滤查询

I just want to ask on how to filter my query with a pivot table. This is how my tables are

users(id,name)

companies(id,name)

users_companies(id,user_id,company_id)

I really want to know how can i filter my list using drop down with pivot table Then this is how it goes to my EloquentUser

   public function paginate($perPage, $search = null, $status = null, $emp_status = null, $level = null, $age = null, $gender = null, $civil_status = null, $role_id = null, $birthmonth = null, $company = null)
    {
    $query = User::query();

    if($company && $company != "" && $company != "All" ) {
            $query->where(function ($q) use ($company) {
                $q->where('id', '=', $company);
            });
        }

This is for my list.blade or where my dropdown is located

<div class="form-group-sm"> 
                <select class="form-control form-control-sm" id="company" name="company">
                    <option selected  disabled>Company</option>
                    @foreach ($companies as $company)
                        @if (($company->id)=="1")
                        <option>All</option>
                        @else
                        <option value="{{ $company->id }}">{{ $company->name }}</option>
                        @endif
                    @endforeach
                </select>
            </div>

Thank you so much experts!!!

You can get users by using whereHas method, here is the example

$selected_company_id = $company; //this is form input, company which you selected

$users = User::whereHas('companies', function ($query) use($selected_company_id) {
    $query->where('company_id', $selected_company_id);
})->get();

This is what i tried and it worked

$query = User::whereHas('benefits', function ($q) use($benefit) {
            $q->where('benefit_id','=', $benefit);
        });