Making-Websites-With-October-CMS
Making-Websites-With-October-CMS copied to clipboard
Use page slug url to limit query in sorting
Hello, I followed every single tutorial and they are awesome. I have slightly upgraded your version of Movie.php model.
What would be the best way to pass page slug from twig file to model (to limit db query).
I have added $slug parameter to onStart function that passes it to Mods model (like yours that was Movie model)
function onStart() {
$this->prepareVars();
}
function onFilterMods() { $this->prepareVars(); }
function prepareVars() {
$slug = $this->param('slug');
$options = post('Filter', []);
$this['mods'] = Mods::listFrontEnd($options, $slug);
$this['brands'] = Brands::all();
$this['category'] = Category::all();
$this['sortOptions'] = Mods::$allowedSortingOptions;
$this['pages'] = $this['mods']->lastPage();
$this['page'] = $this['mods']->currentPage();
}
?>
Page url slug is passed to model without any problems. I inserted $slug variable into last query. That checks if slug same as mods slug and returns only items that have same slug.
Problem is when use sort or brands filter (in your case was genres), then $slug variable becomes empty.
SQL Query on first page load ($slug works)
SQL Query after using sorting or brands (in your case this was genres filter), $slug becomes empty
public function scopeListFrontEnd($query, $options = [], $slug = ''){
extract(array_merge([
'page' => 1,
'perPage' => 4,
'sort' => 'brandName desc',
'brands' => null,
'categorySlug' => null,
], $options));
print $slug; //THis works
if(!is_array($sort)) {
$sort = [$sort];
}
foreach ($sort as $_sort){
if(in_array($_sort, array_keys(self::$allowedSortingOptions))){
$parts = explode(' ', $_sort);
if(count($parts) < 2){
array_push($parts, 'desc');
}
list($sortField, $sortDirection) = $parts;
$query->orderBy($sortField, $sortDirection);
}
}
if($brands !== null) {
if(!is_array($brands)){
$brands = [$brands];
}
foreach ($brands as $brand){
$query->orwhereHas('brand', function($q) use ($brand){
$q->where('brand_id', '=', $brand);
});
}
}
$lastPage = $query->paginate($perPage, $page)->lastPage();
if($lastPage < $page) {
$page = 1;
}
return $query->orwhereHas('category', function($q) use ($slug){
$q->where('slug', '=', $slug);
})->paginate($perPage, $page);
}
Could anyone know what i'm doing wrong here, why $slug becomes empty when using sorting or brands filtering?