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

djolefjc's avatar

Best place in project to define query scope if there is no model?

So, I'm working on upgrading an old project to a newer version. The thing is, the project has a certain search filter if I might call it that way. An old collague of mine who built that app made that search filter with nested if statements and it works perfectly but the code is a nightmare. After looking online I found that the most neat way to make that search filter is with a query scope, which is usually defined in a model but the thing is I don't have a model for that search filter.

So my question is, would it be bad if I defined it in a controller?

0 likes
3 replies
RoboRobok's avatar

If you want to put it inside a controller, I'm assuming there is only one page using it. You can just place this login inside your controller action if it's not useful anywhere else.

JohnBraun's avatar

I assume you are applying your search filter to certain Models, right?

Then, you could make a trait:

<?php 

trait Searchable
{
    public function scopeFilterOne($query, $parameter)
    {
        return $query->where('filter', $paramter);
    }

    public function scopeFilterTwo($query)
    {
        // ...etc
    }
}

Next, on certain models you want to apply this filter to:

<?php

class Item extends Model
{
    use Searchable;

    // ....
}

And in your controller:

<?php

namespace App\Http\Controllers;

public function search() 
{

    // perform your query scope
   $items = Item::filterOne($parameter)->filterTwo()->get();
}

Please or to participate in this conversation.