Reputation: 453
I want to make a complex search on a table with 20 columns.
The user has a form in which he can choose from 0 to 18 criteria to make the search. I capture these criteria in a controller method and return the result to a view. The problem is that I don’t know how to construct the query. I tried with 2 criteria, with the below function, but it doesn’t return a collection, it’s very strange to me what the output of dd($items
) is. Anyway, the function doesn’t return anything if I remove dd($items)
, it’s like it doesn’t find anything in the table (which is impossible because I inserted the criteria in such a way that the function should return something).
public function looksomething($param1=null,$param2=null){
$query= "all()->";
if($param1!=null)
$query.="where(’Field1’,’$param1’)"."<br>->";
if($param2!=null)
$query.="where(’Field2’,’$param2’)"."<br>->";
$query.="get()";
$items=tablename::query();
return view('someview’,['items'=>$items]);
}
So, in the above function, you can see how I thought I should buid my search query. It resembles the model I had for classic php. First, I don’t know what I’m doing wrong. Second, does Laravel have some built-in mechanism that builds complex search query ?
Upvotes: 1
Views: 5299
Reputation: 39389
For simple searching, you could define a scope method in your model that takes an array of parameters as the second argument, and then adds any clauses you need. Something like this:
class SomeModel extends Model
{
public function scopeFilter($query, array $request)
{
if ($request->has('column')) {
$query = $query->where('column', '=', $request->get('column'));
}
// And so on...
return $query;
}
}
Then you can just pass request parameters from your controller action to your model:
public function index(Request $request)
{
$results = SomeModel::filter($request->all())->paginate();
return view('some.view', compact('results'));
}
Upvotes: 4