Skip to content

Commit 3a828a6

Browse files
committed
Caching requests
1 parent 87dbdeb commit 3a828a6

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

app/Models/UserData.php

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace App\Models;
44

55
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Support\Facades\Cache;
67

78
class UserData extends Model
89
{
@@ -11,7 +12,7 @@ class UserData extends Model
1112

1213
public static function saveData($userId, $key, $value)
1314
{
14-
$userData = self::where('id', $userId)->first();
15+
$userData = self::getCachedUserData($userId);
1516

1617
if (!$userData) {
1718
return "null";
@@ -22,35 +23,51 @@ public static function saveData($userId, $key, $value)
2223

2324
$userData->image = json_encode($data);
2425
$userData->save();
26+
27+
self::cacheUserData($userId, $userData);
2528
}
2629

2730
public static function getData($userId, $key)
2831
{
29-
$userData = self::where('id', $userId)->first();
30-
32+
$userData = self::getCachedUserData($userId);
33+
3134
if (!$userData || !$userData->image) {
3235
return "null";
3336
}
34-
37+
3538
$data = json_decode($userData->image, true) ?? [];
36-
39+
3740
return isset($data[$key]) ? $data[$key] : null;
3841
}
3942

4043
public static function removeData($userId, $key)
4144
{
42-
$userData = self::where('id', $userId)->first();
43-
45+
$userData = self::getCachedUserData($userId);
46+
4447
if (!$userData || !$userData->image) {
4548
return "null";
4649
}
47-
50+
4851
$data = json_decode($userData->image, true) ?? [];
49-
52+
5053
if (isset($data[$key])) {
5154
unset($data[$key]);
5255
$userData->image = json_encode($data);
5356
$userData->save();
57+
58+
self::cacheUserData($userId, $userData);
5459
}
5560
}
61+
62+
private static function getCachedUserData($userId)
63+
{
64+
return Cache::remember('user_data_' . $userId, now()->addMinutes(10), function () use ($userId) {
65+
return self::where('id', $userId)->first();
66+
});
67+
}
68+
69+
private static function cacheUserData($userId, $userData)
70+
{
71+
Cache::put('user_data_' . $userId, $userData, now()->addMinutes(10));
72+
}
5673
}

0 commit comments

Comments
 (0)