Skip to content

Instantly share code, notes, and snippets.

@arlanram
Last active March 28, 2021 09:42
Show Gist options
  • Save arlanram/13d2904bad983c5ce6bb118c3fbae580 to your computer and use it in GitHub Desktop.
Save arlanram/13d2904bad983c5ce6bb118c3fbae580 to your computer and use it in GitHub Desktop.
Laravel: search for items and filter by any statement and dynamically add or remove them with depended conditions
<?php
namespace App\Http\Controllers;
class PostController extends Controller
{
//i recommend to use shortened version like sid, hid and tid
protected array $ids = [
'some_id',
'hello_id',
'type_id',
];
protected array $bools = [
'bool1',
'bool2',
'bool3',
];
//don't use primary values, make references like integers and so on
protected array $sorts = [
1 => ['views', 'desc'],
2 => ['views', 'asc'],
3 => ['price', 'desc'],
4 => ['price', 'asc'],
];
public function index(): array
{
//this db comes from main Controller as included DI to construct
$posts = $this->db->table('posts');
foreach ($this->ids as $key => $id) {
if (is_numeric(request($key))) {
$posts->where($id, '=', request($key));
}
}
//predictive search with insensitive to upper & lower cases
if (request('q')) {
$posts->where('title', 'like', '%' . request('q') . '%');
}
//numeric because bool in db stores as tinyint, you can specify and change them with model's cast attribute
foreach ($this->bools as $bool) {
if (is_numeric(request($bool)) === true) {
$posts->where($bool, '=', true);
}
}
if (is_numeric(request('from'))) {
$posts->where('price', '>', request('from'));
}
if (is_numeric(request('to'))) {
$posts->where('price', '<', request('to'));
}
foreach ($this->sorts as $key => $sort) {
if (request('sort') === $key) {
$posts->orderBy($sort[0], $sort[1]);
}
}
//return as array with pagination
return $posts->paginate()->toArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment