@@ -15,25 +15,19 @@ public function index(Request $request)
1515 {
1616
1717 if ($ request ->user ()) {
18+ $ cacheKey = 'user_preferences_ ' .$ request ->user ()->id ;
19+ $ userPreferences = Cache::get ($ cacheKey );
20+ $ locationData = $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]);
1821
19- // Get the cached user preferences
20- $ userPreferences = Cache::get ('user_preferences_ ' .$ request ->user ()->id );
21-
22- // Compare the user preferences with the request
23- if ($ request ->filled ('coordinates ' ) && $ request ->filled ('radius ' ) && $ request ->filled ('city ' ) && $ request ->filled ('postcode ' )) {
24- if (! $ userPreferences || $ userPreferences ['coordinates ' ] !== $ request ->coordinates || $ userPreferences ['radius ' ] !== $ request ->radius || $ userPreferences ['city ' ] !== $ request ->city || $ userPreferences ['postcode ' ] !== $ request ->postcode ) {
25- // Update the user preferences
26- $ request ->user ()->update ([
27- 'preferences ' => $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]),
28- ]);
29- // Store the user preferences in the cache
30- Cache::put ('user_preferences_ ' .$ request ->user ()->id , $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]), 60 * 60 * 24 * 30 );
31- $ userPreferences = $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]);
32- }
22+ if ($ this ->hasValidLocationData ($ request ) && $ this ->shouldUpdatePreferences ($ userPreferences , $ locationData )) {
23+ $ request ->user ()->update (['preferences ' => $ locationData ]);
24+ Cache::put ($ cacheKey , $ locationData , now ()->addDays (30 ));
25+ $ userPreferences = $ locationData ;
26+ } else {
27+ $ userPreferences = null ;
3328 }
34-
3529 } else {
36- $ userPreferences = $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]);
30+ $ userPreferences = $ this -> hasValidLocationData ( $ request) ? $ request ->only (['coordinates ' , 'radius ' , 'city ' , 'postcode ' ]) : null ;
3731 }
3832
3933 $ query = Equipment::query ()
@@ -110,4 +104,14 @@ public function index(Request $request)
110104 'stats ' => $ stats ,
111105 ]);
112106 }
107+
108+ private function hasValidLocationData (Request $ request )
109+ {
110+ return $ request ->filled ('coordinates ' ) && $ request ->filled ('radius ' ) && $ request ->filled ('city ' ) && $ request ->filled ('postcode ' );
111+ }
112+
113+ private function shouldUpdatePreferences ($ userPreferences , $ locationData )
114+ {
115+ return ! $ userPreferences || $ userPreferences ['coordinates ' ] !== $ locationData ['coordinates ' ] || $ userPreferences ['radius ' ] !== $ locationData ['radius ' ] || $ userPreferences ['city ' ] !== $ locationData ['city ' ] || $ userPreferences ['postcode ' ] !== $ locationData ['postcode ' ];
116+ }
113117}
0 commit comments