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

fortee's avatar

How to filter collection based on relationships attribute

I want to filter my model collection based on the related models attribute. My status model has an attribute of name. When I do:

$stores = Store::all()

How am I able to filter $stores based on the related status names?

Doing this from a controller, or even with a helper method doesen't seem ok with me:

Store::whereHas('status', function ($query) use ($name){
        $query->where('name', $name);
    })->get();

These are my two models:

class Store extends Model
{
    public function status()
    {
        return $this->belongsTo(Status::class);
    }
}
class Status extends Model
{
public function stores()
    {
        return $this->belongsToMany(Store::class);
    }
}

If I want a view with multiple filters that means multiple queries. What would be the best way to do this?

0 likes
3 replies
TorbenDaudistel's avatar

Are you sure, that the "belongsToMany" relationship is correct? Try a hasMany relationship instead.

squigg's avatar
squigg
Best Answer
Level 2

Try using a status scope:

// In Store Model
public function scopeStatus (Builder $query, $name) {
    return $query->whereHas('status', function ($q) use ($name) {
            $q->where('name', $name);
    });
}

$stores = Store::status('statusname')->get();
4 likes

Please or to participate in this conversation.