To store the results of a date range in cache so that when you leave a page to another (pagination) Laravel yajra datatable server-side no longer launches the query in the database to display the results, you can use Laravel's cache system. Here's how you can do it:
-
First, you need to add the
use Illuminate\Support\Facades\Cache;statement at the top of your controller file. -
Then, you can modify your
paydrc_daterangefunction to use the cache. Here's an example:
public function paydrc_daterange(Request $request)
{
$transactions = [];
if (request()->ajax()) {
$transactions = Cache::remember('transactions_' . md5(json_encode($request->all())), 60, function () use ($request) {
$transactions = [];
if (!empty($request->start_date)) {
$dateStart = date('Y-m-d', strtotime($request->start_date));
$dateEnd = date('Y-m-d', strtotime($request->end_date));
$curl_post_data = ["dateStart" => $dateStart, "dateEnd" => $dateEnd, "action" => $request->action];
$url = "http://127.0.0.1:8086/services/paydrc/daterange";
$data = json_encode($curl_post_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$curl_response = curl_exec($ch);
if ($curl_response == false) {
$transactions = [];
} else {
$transactions = json_decode($curl_response, true);
}
}
return $transactions;
});
return datatables()->of($transactions)->make(true);
}
if (Auth::user()->is_user == 3) {
return view('_finance.transaction.paydrc_daterange');
}
}
In this example, we're using the Cache::remember method to store the results of the query in the cache for 60 seconds. The cache key is generated based on the request parameters using the md5 function. If the cache already contains the data, it will be returned from the cache instead of running the query again.
Note that you can adjust the cache time to suit your needs. Also, make sure to clear the cache when necessary, for example, when new data is added to the database.
That's it! With this solution, the results of the query will be stored in the cache, and when you leave the page and come back, the data will be retrieved from the cache instead of running the query again.