Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Build dynamic filter controls in Laravel - https://simplestweb.in/blog/dynamic-filter-controls-laravel
public function index(Request $request)
{
$sortBy = 'id';
$orderBy = 'desc';
$perPage = 20;
$q = null;
if ($request->has('orderBy')) $orderBy = $request->query('orderBy');
if ($request->has('sortBy')) $sortBy = $request->query('sortBy');
if ($request->has('perPage')) $perPage = $request->query('perPage');
if ($request->has('q')) $q = $request->query('q');
$users = User::search($q)->orderBy($sortBy, $orderBy)->paginate($perPage);
return view('users.index', compact('users', 'orderBy', 'sortBy', 'q', 'perPage'));
}
<form action="{{ route('users.index') }}">
<div class="row">
<div class="col-md-4">
<input class="form-control form-control-sm" type="search" name="q" value="{{ $q }}">
</div>
<div class="col-md-2 col-3">
<select name="sortBy" class="form-control form-control-sm" value="{{ $sortBy }}">
@foreach(['id', 'name', 'email', 'notes'] as $col)
<option @if($col == $sortBy) selected @endif value="{{ $col }}">{{ ucfirst($col) }}</option>
@endforeach
</select>
</div>
<div class="col-md-2 col-3">
<select name="orderBy" class="form-control form-control-sm" value="{{ $orderBy }}">
@foreach(['asc', 'desc'] as $order)
<option @if($order == $orderBy) selected @endif value="{{ $order }}">{{ ucfirst($order) }}</option>
@endforeach
</select>
</div>
<div class="col-md-2 col-3">
<select name="perPage" class="form-control form-control-sm" value="{{ $perPage }}">
@foreach(['20','50','100','250'] as $page)
<option @if($page == $perPage) selected @endif value="{{ $page }}">{{ $page }}</option>
@endforeach
</select>
</div>
<div class="col-md-2 col-3">
<button type="submit" class="w-100 btn btn-sm bg-blue">Filter</button>
</div>
</div>
</form>
public function scopeSearch($query, $q)
{
if ($q == null) return $query;
return $query
->where('name', 'LIKE', "%{$q}%")
->orWhere('email', 'LIKE', "%{$q}%")
->orWhere('website', 'LIKE', "%{$q}%")
->orWhere('twitter', 'LIKE', "%{$q}%")
->orWhere('notes', 'LIKE', "%{$q}%");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.