Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

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

    }
8 months 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);
}
8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs