See this page
https://speakernet.co.uk/talks
and the filters that are in the top right of the page
In the controller, I use Scopes to filter the records, so the main part of the method looks like;
public function talks()
{
$filters = $this->filters;
// get topics, filtered by adding local scopes through the Topic class
$talks = Topic::with('speaker.region','tagged','category')
->regions($filters['region'])
->category($filters['category'])
->fee($filters['fee'])
->recency($filters['recency'])
->tagged($filters['tagged'])
->published()
->notice($filters['notice'])
->orderBy('subject')
->paginate(15);
and in the model, the talks are filtered by scopes such as;
public function scopeCategory($query,$category)
{
if($category!=""){
return $query->where('category_id',$category);
}
return $query;
}
public function scopeFee($query,$fee)
{
if(!Empty($fee)){
return $query->where('fee_id',$fee);
}
return $query;
}
To work from page to page, the filters are persisted in the session, so when the index page is loaded, its applying all the filters it already has in session for this user
So there are a bunch of functions which are related to saving state in session
public function initialiseFilters()
{
//ensure that the filters are setup in session and hydrated into controller
$this->filters = session('filters');
if(!isset($this->filters)) {
$this->resetFilters();
}
}
private function resetFilters()
{
// create empty filters
$this->filters = [
'category' => '',
'fee' => '',
'region' => '',
'recency' => '',
'notice' => '',
'tagged' => '',
'filtered' => false]
;
session(['filters' => $this->filters]);
}
private function saveFilters()
{
// save updated filters to the session
session(['filters' => $this->filters]);
}
private function unsetFilter($filter)
{
$this->initialiseFilters();
$this->filters[$filter] = '';
$this->setFilteredFlag();
return $this->saveFilters();
}
private function setFilteredFlag()
{
$f = $this->filters;
if (!
empty($f['region'])
|| !empty($f['category'])
|| !empty($f['fee'])
|| !empty($f['recency'])
|| !empty($f['notice'])
|| !empty($f['tagged']))
{
return $this->filters['filtered']= true;
}
return $this->filters['filtered']= false;
}
When you change one of the dropdowns on the page, it updates the session with the new value, then loads the index where the database is queried using the new value that is in session.
public function category(Request $request, $category)
{
$this->initialiseFilters();
$this->filters = array_merge($this->filters,['category' => $category, 'filtered' => true]);
$this->saveFilters();
return $this->talks();
}