Patrick Schocke
Patrick Schocke

Reputation: 1491

Laravel get relations from a many to many relations

I have 3 models: User, Company and Vacancie.

The Models have the following relations:

User many to many Company

Company one to many Vacancie

How can I get all Vacancie a User has access to?

I've found this answer but auth()->user()->with('companies.vacancies')->get(); returns all users of my database.

Upvotes: 1

Views: 81

Answers (2)

Laerte
Laerte

Reputation: 7073

You can do something like this:

$userId = $request->user_id;
$vacancies = Vacancie::whereHas('companies', function ($q) use ($userId){
    $q->whereHas('users', function($q1) use ($userId) {
        $q1->where('users.id', userId);
    });
})->get();

In this code, I'm considering that you have the relations companies() in Vacancie and users() in Company.

This will do the inverse of what you are doing now. When you call get() in the user model, you will get all the users with the relations pré-loaded (with()).

Upvotes: 1

Elisha Senoo
Elisha Senoo

Reputation: 3594

Create a vacancies relationship on the User model as follows:

//inside the User model
public function vacancies()
    {
        $vacancies= new Illuminate\Database\Eloquent\Collection;

        foreach($this->companies as $company)
        {
            $vacancies = $vacancies->merge($company->vacancies->get());
        }

        return $vacancies->unique();
    }

Then you can do auth()->user()->with('vacancies')->get(). Not tested, but the general idea holds.

Upvotes: 0

Related Questions