LinkStack/app/Models/UserData.php

74 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
2023-12-16 19:09:38 +01:00
use Illuminate\Support\Facades\Cache;
class UserData extends Model
{
protected $table = 'users';
protected $fillable = ['image'];
public static function saveData($userId, $key, $value)
{
2023-12-16 19:09:38 +01:00
$userData = self::getCachedUserData($userId);
if (!$userData) {
2023-02-16 16:10:41 +01:00
return "null";
}
2023-02-16 16:10:41 +01:00
$data = json_decode($userData->image, true) ?? [];
$data[$key] = $value;
$userData->image = json_encode($data);
$userData->save();
2023-12-16 19:09:38 +01:00
self::cacheUserData($userId, $userData);
}
public static function getData($userId, $key)
{
2023-12-16 19:09:38 +01:00
$userData = self::getCachedUserData($userId);
if (!$userData || !$userData->image) {
2023-02-16 16:10:41 +01:00
return "null";
}
2023-12-16 19:09:38 +01:00
2023-02-16 16:10:41 +01:00
$data = json_decode($userData->image, true) ?? [];
2023-12-16 19:09:38 +01:00
return isset($data[$key]) ? $data[$key] : null;
}
public static function removeData($userId, $key)
{
2023-12-16 19:09:38 +01:00
$userData = self::getCachedUserData($userId);
if (!$userData || !$userData->image) {
2023-02-16 16:10:41 +01:00
return "null";
}
2023-12-16 19:09:38 +01:00
2023-02-16 16:10:41 +01:00
$data = json_decode($userData->image, true) ?? [];
2023-12-16 19:09:38 +01:00
if (isset($data[$key])) {
unset($data[$key]);
$userData->image = json_encode($data);
$userData->save();
2023-12-16 19:09:38 +01:00
self::cacheUserData($userId, $userData);
}
}
2023-12-16 19:09:38 +01:00
private static function getCachedUserData($userId)
{
return Cache::remember('user_data_' . $userId, now()->addMinutes(10), function () use ($userId) {
return self::where('id', $userId)->first();
});
}
private static function cacheUserData($userId, $userData)
{
Cache::put('user_data_' . $userId, $userData, now()->addMinutes(10));
}
}