• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

127
Views
Retrieve all models that are not associated with another model through pivot

I have three tables: users, organizations, organization_user. organization_user is a pivot table for the many-to-many relationship between users and organizations. The many-to-many relationships have been setup correctly in the corresponding models.

I need to obtain all users who are not associated with a given organization. How should this be done using eloquent. Below is what I have tried, but it is returning no results:

public function associate_user($organization_id){

        $data = [
            'organization'      => \App\Organization::find($organization_id),
            'users'             => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
                $query->where('organization_id', $organization_id);
            })
        ];

        return view('admin.associateUser', $data);

    }
over 3 years ago · Santiago Trujillo
1 answers
Answer question

0

You are never actually executing the query.

You need to call get() at the end of the query builder.

public function associate_user($organization_id) {
    $data = [
        'organization' => \App\Organization::find($organization_id),
        'users'        => \App\User::whereDoesntHave('organizations', function($query) use ($organization_id){
            $query->where('organization_id', $organization_id);
        })->get(); // Add the call to get()
    ];
    return view('admin.associateUser', data);
}
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error