public function search(Request $request)
{
$dresses = Dresses::query();
if($request->has('price'))
{
$dresses->where('price', $request->get('price'));
}
$dresses->paginate(10);
return view('dresses.index', compact('dresses'));
}
Multiple Where Clauses from GET Variables
All,
So, I am in a bit of a bind. I have sat and fumbled with a lot of options but nothing seems to be working for me.
Here is what I am trying to do: I have a search form that is searching a "dresses" table. Standard fields like price, length, color, etc. I know I can do multiple where clauses for all of the fields that get passed and then return a paginated collection, but I do not know how to address the issue of when a field does NOT get passed. Say someone chooses not to do a search on the length and is only concerned with the price. How do I handle that GET variable that is not passed or is empty because I found I cannot use an empty string in the ->where() clauses.
Is there a way to make those where clauses dynamic? For example, check to see if a variable is set and then make insert another where clause, or, if it is not set to just skip over it? Is this something I could extract to a class and build up a query to be returned to the controller?
Any advice, and I mean any at all would be greatly appreciated.
R,
@deevoweb For simple filtering, I’ve added a scope to my model that I can pass an array of parameters to, and the scope will add the relevant clauses. An example:
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
class Dress extends Model
{
public function scopeFilterByRequest($query, Request $request)
{
if ($request->has('color')) {
$query->where('color', '=', $request->get('color'));
}
if ($request->has('size')) {
$query->where('size', '=', $request->get('size'));
}
// And so on
return $query;
}
}
Usage:
public function index(Request $request)
{
$dresses = Dress::filterByRequest($request)->paginate();
return view('dresses.index', compact('dresses'));
}
Hope that helps.
Please or to participate in this conversation.