My question is, if there is data in the cache, I created a condition by saying fetch, and if not, I bring it from the database and refresh the cache for a certain period of time. Normally, if I don't use the cache, I can search the page, but I cannot search by id or nickname with the code below.So when using cache::get can I add a search condition?
public function index(Request $request)
{
$submit = $request->get('submit');
$id = $request->get('id');
$nick_name = $request->get('nick_name');
if (Cache::has('users')) {
$users = Cache::get('users');
return view('admin.users.index', compact('users'));
}
$users = User::when(!empty($id), function ($query) use ($id) {
$query->where('id', $id);
})->when(!empty($nick_name), function ($query) use ($nick_name) {
$query->where('nick_name', $nick_name);
})->orderBy('created_at', 'asc')->get();
Cache::put('users', $users, now()->addMinutes(60));
return view('admin.users.index', compact('users'));
}
CodePudding user response:
You should add search criteria in your cache key. E.g.
public function index(Request $request) {
$submit = $request->get('submit');
$id = $request->get('id');
$nick_name = $request->get('nick_name');
$cacheKey = User::class . md5(json_encode([$submit, $id, $nick_name]));
if (Cache::has($cacheKey)) {
/* ... */
}
because now your cache writes only first search result and ignores everything else.
Or write to cache all users. Then run that array through array_filter
applying filters. But that can be waste of developer time if search is very dynamic.