I am trying to add simple sorting to my index pages, but I am coming into conflict when I try to include search results or add an additional query to the URL. Here is what I currently have:
Controller
// Search default
if ($request->search == null) {
$search = '';
} else {
$search = $request->search;
}
// Sort default
if ($request->sort == null) {
$sort = 'asc';
} else {
$sort = $request->sort;
}
$doctors = Doctor::orderBy('last_name', $sort)
->where('first_name', 'LIKE', '%' . $search . '%')
->orWhere('last_name', 'LIKE', '%' . $search . '%')
->orWhere('type', 'LIKE', '%' . $search . '%')
->orWhere('npi', 'LIKE', '%' . $search . '%')
->orWhere('license', 'LIKE', '%' . $search . '%')
->orWhere('dea', 'LIKE', '%' . $search . '%')
->paginate(10);
return view('doctors.index')->with('doctors', $doctors);
Blade
{{ Form::open(['method' => 'GET']) }}
{{ Form::text('search', null, ['class' => 'form-control form-control-sm', 'placeholder' => 'Search Doctors...']) }}
{{Form::submit('Search', ['class' => 'btn btn-primary btn-sm'])}}
{{ Form::close() }}
@if(Request::input('sort', 'asc') == 'asc')
<a href="?sort=desc">Name</a>
@else
<a href="?sort=asc">Name</a>
@endif
Now, independently, the ?search=
and the ?sort=
will work. But if I try to search for something, then sort the results, it clears out the search request. I also have other columns such as License#, Address, etc that I want to add so that people can sort by more than just the Name. However, when I change the requests to add a ?sortBy=
such as<a href="?sortBy=name?sort=desc">Name</a>
, the sort direction no longer works.