Laravel - get rows not in custom hasMany relationship

613 views Asked by At

I have an admin table and admin has many form. Each form is assigned to an admin that is displayed on their dashboard.

The trouble is there can be form that is that is not assigned to any admin.

I want to get all those forms Any help is appreciated. Thank you!

Edit : Admin is related to form via a custom relation as described Here

To summarize,

Admin.php

public function states(){
    return $this->belongsToMany('App\State');
}

public function cities()
{
    return $this->belongsToMany('App\City');
}

//gets the forms in  this admin's city or state
//Let me know if there is a better way to do this, i feel like im overdoing stuff here 
public function forms()
{  
        //cities
        $cities = $this->cities->pluck('name'); 
        //states
        $states = $this->states->pluck('name');

        $users =  User::whereIn('state',$states)>orWhereIn('city',$cities)->get()->pluck('id');

        $forms = Form::whereIn('user_id',$users);

        return $forms;

}

Id like to get the form that doesnt belong to any admin

2

There are 2 answers

1
Sanzeeb Aryal On

You may be looking for doesntHave.

$forms=Form::doesntHave('admin')->get();
0
prateekkathal On

Why don't you simply do the reverse of it?

$forms = Form::whereNotIn('user_id', $users);