I have a function that gets a list of maps from the database. It is necessary to improve it so that when passing through $ request fields for search (series, number, balance) a corresponding query is built (there may be more fields, a large number of if else is not an option).

public function card_list(Request $request) { $q = $request->input('card') ; $this->data['cards'] = Card::where('id', '>', 0)->paginate(15); return view('pages.card_list', $this->data); } 
  • The question is actually how to correctly implement this in Laravel 5.2 - David

1 answer 1

This is how I implemented :

 trait FindByRequestTrait { public function scopeFindByRequest($query, $request = NULL) { if (is_null($request)) { $request = Input::all(); } $findable = isset($this->findable) ? $this->findable : []; foreach ($request as $field => $value) { if (!in_array($field, $findable)) { continue; } // специфические условия обрабатываются отдельно // ... см. по линке // остальные вот так if (is_array($value)) { $query->whereIn($field, $value); } elseif (is_scalar($value)) { $query->where($field, '=', $value); } } } } 

phpDoc and tag search are removed from the example, but there is in github

In the model, you need to add a new property $findable with fields by which you can search and connect the treyt:

 class Card extends Model { use FindByRequestTrait; protected $findable = ['id', ...]; // ... } 

Using:

 Card::findByRequest()->paginate(15);