Last active
July 12, 2024 13:20
-
-
Save rootchips/1fb49cbb8aa97b32899b99a3b860c99c to your computer and use it in GitHub Desktop.
How to use cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using Redis + Cache replacement for laravel | |
// composer require swayok/alternative-laravel-cache | |
// | |
<?php | |
namespace App\Http\Controllers; | |
use App\Models\Data; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Cache; | |
class DataController extends Controller | |
{ | |
public function all(Request $request) | |
{ | |
$key = "data-page-{$request->page}"; | |
$key .= "-search-{$request->search}"; | |
$data = Cache::tags(['data'])->rememberForever($key, function () use ($request) { | |
return tap(Data::query() | |
->search($request) | |
->paginate(10), function ($paginatedInstance) { | |
return $paginatedInstance->getCollection()->transform(function ($data, $key) { | |
return [ | |
// to display your data | |
'your_data' => $data->your_data | |
]; | |
}); | |
}); | |
}); | |
return response()->json($data); | |
} | |
public function create(Request $request) | |
{ | |
// Create code | |
Cache::tags(['data'])->flush(); // need to flush to renew the latest data | |
} | |
public function update(Data $data, Request $request) | |
{ | |
// Update code | |
Cache::tags(['data'])->flush(); // need to flush to renew the latest data | |
} | |
public function destroy(Data $data, Request $request) | |
{ | |
// Delete code | |
Cache::tags(['data'])->flush(); // need to flush to renew the latest data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment