To get tenants that have the name "admin" for a particular apartment, you can use the wherePivot method in Laravel's Eloquent ORM. Here's an example of how you can modify the tenants method in the Apartment model:
class Apartment extends Model
{
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class)
->wherePivot('role_id', function ($query) {
$query->from('roles')->where('name', 'admin');
});
}
}
This code adds a constraint to the relationship query using the wherePivot method. It checks the role_id column in the pivot table (apartment_tenant) and filters the tenants based on the name column in the roles table.
Now, when you call the tenants relationship on an instance of the Apartment model, it will only return the tenants with the name "admin" for that particular apartment.
$apartment = Apartment::find(1);
$adminTenants = $apartment->tenants;
Note: Make sure to replace 1 with the actual ID of the apartment you want to retrieve the tenants for.