1

I have an application where users can control their properties and leases.

These are the relationships defined:

//Team.php
/**
 * A team can have many properties.
 */
public function properties():
{
    return $this->hasMany(Property::class);
}
//Property.php
/**
 * A property can have many leases.
 */
public function leases():
{
    return $this->hasMany(Lease::class);
}

As you can see here, a Team can have many properties, and each property can also have many leases.

I am trying to figure out how I can get the number of leases that is associated with a Team:

$team = Auth::user()->currentTeam;

return $team->properties->leases->count();

However, the above code returns an error:

Property [leases] does not exist on this collection instance.

3
  • 1
    You're have to iterate properties; that's a Collection of Property instances, so calling ->properties->leases won't work as it doesn't know which property->leases you're referencing. There's a hasManyThrough(), but it doesn't work for nested many-to-many, but hasManyDepp(), via this package does. Commented Sep 24, 2021 at 15:05
  • @TimLewis After reading a bit more about hasManyThrough I do believe I can use it actually. (See my proposed answer) Commented Sep 26, 2021 at 9:17
  • 1
    Nice! I misread your question a bit, you don't quite have a nest many-to-many like I originally thought, you have nested one-to-many (one Team -> many Properties -> many Leases), so hasManyThrough should actually work just fine here. Glad you got it working regardless! Commented Sep 27, 2021 at 0:36

2 Answers 2

1

You could add this method to your Team.php:

public function leasesCount(){
    return count(
        Team::
            join('properties', 'properties.team_id', '=', 'teams.id')
            ->join('leases', 'leases.property_id', '=', 'properties.id')
            ->where('teams.id', $this->id)
            ->get()
    );
}
Sign up to request clarification or add additional context in comments.

Comments

1

I ended up using a hasManyThrough relationship on the Team model, like so:

//Team.php

/**
 * Get all of the leases for the team.
 */
public function leases()
{
    return $this->hasManyThrough(Lease::class, Property::class);
}

Then I can simply get the number of leases created by a specific team by:

return $team->leases()->count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.