Using method trait to return something in laravel model
I have question about scope yesterday, and someone gives an answer to don't return anything in scope. Is return something in scope really bad practice?


This is because laravel is handling &quot;it&quot; for you.

getSelect2Format is not the best name since you are not handling formatting but apply a specific set of rules relevant to select2 js plugin.

I would suggest a repository class or a helper class to handle this task.

Your code is messy, very long lines too, which is hard to read! I would suggest following PSR-12.

I would suggest using response() or just return $data in controller class methods.

I would also suggest early returns in your methods to reduce nesting hence easy reviewing by reviewers.

suggest not using -&gt;get() in a method unless you are absolutely certain on what method should do. i.e. you might want to apply a scope to this query  later on.

I suggest passing request data into the class to make it easier to test. Also, the less your class knows about other parts of the system the better.

Dont you have to use DB::raw for $column.' as text'?


class select2Filters
{
    public static function apply(
        Model $model, 
        array $data, 
        string $column = 'name', 
        int $limit = 5
    ) {
        $filter = Arr::get($data, 'filter');
    
        return $model::selectRaw(['id', &quot;{$column} as text&quot;])
             -&gt;where($column, 'like', &quot;%{$data['q']}%&quot;)
             -&gt;when(is_array($filter), function($query) use ($filter) {
                 $query-&gt;where(Arr::only($filter, $model::filterable)); 
             })
             -&gt;orderBy($column, 'asc')
             -&gt;limit($limit)
             -&gt;get();
    }
}

I would also suggest adding an interface to each model that should have support for select2Filters. That interface should inforce filterable variable.
I would personally not use static, that way you can add configuration methods, i.e. setLimit(). OR use data struct class to contain data needed for select2Filters class.