Level 5
Are you sure, that the "belongsToMany" relationship is correct? Try a hasMany relationship instead.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
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();
Please or to participate in this conversation.