1

I have multiple search functions that all look something like this:

    public function searchEntity(Request $request)
    {       
        ... // Some variables and other stuff 

        $q = $request->q;
        $entities = Entity::where('name', 'LIKE', '%' . $q . '%')->paginate(15);
        $entities->appends(['search' => $q]);
        return view(
            'entity',
            compact('entities', ...)
        );
    }

Is there a better way to do this where I don't repeat the same code each time I try to search an Eloquent entity or is it better to keep these methods separate?

5eb
  • 14,798
  • 5
  • 21
  • 65

1 Answers1

3

My suggestion is to create Trait with scope.

So you will have something like this in your trait:

trait search
{
    public function scopeSearch(Builder $builder)
    {
        $request = request();
        $q = $request->q;

        return $builder->where('name', 'LIKE', '%' . $q . '%')->paginate(15);
    }

}

Than use your trait in your model. And in your controller for every model you can do like this:

$entities = Entity::search();

Just read about Traits and Scopes and I think that's what you need.

Some suggestions: link-1, link-2.

Good luck!

mare96
  • 3,749
  • 1
  • 16
  • 28