2

I am trying to figure out how to achieve the following. I have searched and searched to no avail.

I have a pivot table in a Laravel 5 app that is working as expected with the following functions in the respective models.

// Module.php
//...
public function sites()
{
    return $this->belongsToMany('App\Site')->withPivot('enabled');
}

// Site.php
//...
public function modules()
{
    return $this->belongsToMany('App\Module')->withPivot('enabled');
}

I can retrieve all relevant records with something like the following in my Sitecontroller.php

$site = Site::with('modules')->findOrFail($id);

The problem i have is i want to be able to get all modules that do not have an associated record in the pivot table for the site in question.

Can anyone point in the right direction how i might achieve something like this, in the right way ( i can think of a few ways but seems really hacky )

Thanks in advance. M

madmatuk
  • 117
  • 4
  • 12

1 Answers1

11

Starting the query from the Module side and excluding with whereDoesntHave should work in this case:

$id = 1;
$modules = Module::whereDoesntHave('sites', function($q) use ($id){
    $q->where('site_id', $id);
})->get();
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • Hi Lukas, I feel stupid now :). I guess my "newishness" has shined :) That did the trick perfectly. – madmatuk Feb 20 '15 at 21:31
  • Don't feel stupid ;) `whereDoesntHave` is rather one of the advanced tricks of Eloquent and unfortunately it isn't mentioned in the documentation either... – lukasgeiter Feb 20 '15 at 21:36
  • I guess so, i couldn't find anything in the context of my search criteria, we live and learn. Thanks again Lukas. – madmatuk Feb 20 '15 at 21:43
  • Thats the best answer rather then using not-in relation or exists method. Thanks – Tarunn Jul 15 '15 at 07:14