1 week ago

How to query though a pivot table?

Posted 1 week ago by fbc

I use a pivot table for assigning roles to contacts:

class Contact extends Model
    protected $fillable = [
    public function roles()
        return $this->belongsToMany('App\Models\contact\ContactRole');


class ContactRole extends Model

    public function contacts()
        return $this->belongsToMany('App\Models\contact\Contact');

I'm trying to put them into as SELECT BOX as so:

                        <select id="contractor_id" class="component form-control" name="contractor_id" required>
                            <option>Pick a General Contractor....</option>
                            @foreach ($project_managers->contacts as $contact)
                            <option value="{{$contact->id}}">{{$contact->first_name}} - {{$contact->last_name}}</option>

however I get:

Property [contacts] does not exist on this collection instance. (View: /root/resources/views/project/create.blade.php)

I'm calling my view like this:

    public function create()
        // $project_managers = Contact::wherePivot($roles(),5)->get();
        $project_managers = ContactRole::where('id', 5)->get(); //Get only the project manager roles
        return view('project.create', compact('project_managers'));

As you can see I've already tried coming at it from another direction but could not make it work, so now I'm trying to come at through the roles.

Please sign in or create an account to participate in this conversation.