Support the ongoing development of Laravel.io →
Database Eloquent

Hi I'm having a struggle trying to return a single record from a many to many relationship.

So in my app I've Clubs and Addresses entities. Clubs have 0, 1 or n Addresses and one of them may be the main address. An Address can also be used by some other entities (like Events, Members etc..)

My tables are the following :

  • clubs: id, name
  • addresses: id, street, city, zip
  • club_address: id, club_id, address_id, is_main

I can currently request all the addresses of my club like so :

Class Club {
    public function addresses()
    {
        return $this->belongsToMany('Address', 'club_address', 'club_id', 'address_id')->withPivot('is_main'); // club_address
    }
}

Now what I'd like is to get the main address or null when I request a club.

I can't be satisfied with simply adding ->wherePivot('is_main', '=', 1) because it's still returning an array of 1 or 0 element when I want an array or null.

Is that possible in Laravel ?

I'd like something like this

Class Club {
    public function address()
    {
        return $this->addresses()->wherePivot('is_main', '=', 1)->first();
    }
}
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.