Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uxweb's avatar

You can use a so called "Query Scope" in your Contact Model, something like this:

http://laravel.com/docs/5.0/eloquent#query-scopes

<?php 

class Contact {
    
    /* Common model fields */
    
    /*
    * Query scope to get just primary contacts
    */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', 1);
    }
}

Then in your view you can access it like this i think:

    $family->contacts->primary()->first_name
fluentd's avatar

Thanks @uxweb I will try it and see if I can get anywhere. I am still trying to figure out where to put everything as it seems my controllers are starting to carry most of my code which I think is wrong.

fluentd's avatar

I am not understanding why the following:

$contacts = Family::find(1)->contacts()->where('is_primary', '=', '1')->get()

works and returns a collection of contacts from the family ID of 1 but when I try to use the following and change find(1) to all() it does not work.

FatalErrorException in FamiliesController.php line 25:
Call to undefined method Illuminate\Database\Eloquent\Collection::contacts()

$contacts = Family::all()->contacts()->where('is_primary', '=', '1')->get()

I have already pulled the latest families using:

$families = Family::latest('created_at')->get();

but now I would also like to get all the related contacts from those families and only display the ones where('is_primary', '=', '1') (I have yet to move that to a queryScope as I wanted to get it working first.

I am guessing the problem is with it being a collection? @uxweb or @blackbird

fluentd's avatar

I changed my syntax to use Eager loading by using the following:

$families = Family::with('contacts')->get();

the following worked and is pulling all families and relationship of contacts for each, but now I am not really sure how to use the array of arrays to display data in my table where it has both family and contact information in the same row.

Previous

Please or to participate in this conversation.