Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F7057809
UserSettingsTrait.php
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
2 KB
Referenced Files
None
Subscribers
None
UserSettingsTrait.php
View Options
<?php
namespace
App\Traits
;
use
App\UserSetting
;
use
Illuminate\Support\Facades\Cache
;
trait
UserSettingsTrait
{
/**
* Obtain the value for a setting.
*
* Example Usage:
*
* ```php
* $user = User::firstOrCreate(['email' => 'some@other.erg']);
* $locale = $user->getSetting('locale');
* ```
*
* @param string $key Lookup key
*
* @return string
*/
public
function
getSetting
(
$key
)
{
$settings
=
$this
->
getCache
();
$value
=
array_get
(
$settings
,
$key
);
return
(
$value
!==
''
)
?
$value
:
null
;
}
/**
* Create or update a setting.
*
* Example Usage:
*
* ```php
* $user = User::firstOrCreate(['email' => 'some@other.erg']);
* $user->setSetting('locale', 'en');
* ```
*
* @param string $key Setting name
* @param string $value The new value for the setting.
*
* @return void
*/
public
function
setSetting
(
$key
,
$value
)
{
$this
->
storeSetting
(
$key
,
$value
);
$this
->
setCache
();
}
/**
* Create or update multiple settings in one fell swoop.
*
* Example Usage:
*
* ```php
* $user = User::firstOrCreate(['email' => 'some@other.erg']);
* $user->setSettings(['locale', 'en', 'country' => 'GB']);
* ```
*
* @param array $data An associative array of key value pairs.
*
* @return void
*/
public
function
setSettings
(
$data
=
[])
{
foreach
(
$data
as
$key
=>
$value
)
{
$this
->
storeSetting
(
$key
,
$value
);
}
$this
->
setCache
();
}
private
function
storeSetting
(
$key
,
$value
)
{
$record
=
UserSetting
::
where
([
'user_id'
=>
$this
->
id
,
'key'
=>
$key
])->
first
();
if
(
$record
)
{
$record
->
value
=
$value
;
$record
->
save
();
}
else
{
$data
=
new
UserSetting
([
'key'
=>
$key
,
'value'
=>
$value
]);
$this
->
settings
()->
save
(
$data
);
}
}
private
function
getCache
()
{
if
(
Cache
::
has
(
'user_settings_'
.
$this
->
id
))
{
return
Cache
::
get
(
'user_settings_'
.
$this
->
id
);
}
return
$this
->
setCache
();
}
private
function
setCache
()
{
if
(
Cache
::
has
(
'user_settings_'
.
$this
->
id
))
{
Cache
::
forget
(
'user_settings_'
.
$this
->
id
);
}
$settings
=
$this
->
settings
()->
get
();
Cache
::
forever
(
'user_settings_'
.
$this
->
id
,
$settings
);
return
$this
->
getCache
();
}
}
File Metadata
Details
Attached
Mime Type
text/x-php
Expires
Fri, Jun 12, 4:08 AM (15 h, 21 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
909774
Default Alt Text
UserSettingsTrait.php (2 KB)
Attached To
Mode
R2 kolab
Attached
Detach File
Event Timeline
Log In to Comment