Skip to content
Advertisement

Filter results by pivot data on laravel / eloquent

I need to filter my data that match a specified criteria, see the example below

DB SCHEME

user

  • id
  • name

company

  • id
  • name

user_company

  • user_id
  • company_id
  • date
  • note

DATA

user

| id | name | | — | —- | | 1 | john | | 2 | jim |

company

| id | name | | — | ———— | | 1 | Google | | 2 | Stackoverflow |

user_company

user_id company_id end_date note
1 2 31/12/2018 Left
1 1 31/12/2020 Fired
1 2 NULL Hired
2 1 NULL Hired

I just wanted to know who and for which company is working actually.

User.php

public function companies() {
  return $this
      ->belongsToMany('AppCompany', 'user_company', 'user_id', 'company_id')
      ->as('company')
      ->withPivot(['end_date', 'note'])
}

my query

$users = User::with('companies')->select(['user.*']);

Already tried using wherePivotNull('end_date') either in model relationship and in controller query, no success.. I still miss something.

Advertisement

Answer

I think using whereHas, we can achieve that

 $users = User::with('companies')
        ->whereHas('companies',function ($query){
            $query->whereNull('user_company.end_date');
        })
        ->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement