Search code examples
laravellaravel-5eloquent

How to Prevent a request from being cached for LANGUAGE SWITCH routing Laravel Spatie responsecache


I am using Laravel Spatie response cache: https://github.com/spatie/laravel-responsecache and Multiple language (language switch..).

How to fix: Preventing a request from being cached for language switcher route in Laravel.

I tried to add: ->middleware('doNotCacheResponse'); in lang.switch route but without success...

Route::get('lang/{language}', ['as' => 'lang.switch', 'uses' => 'LanguageController@switchLang'])->middleware('doNotCacheResponse');

Expected results to prevent request when switching pages (links) between language to be cached....


Solution

  • Not sure if I understand you correctly. If the problem is that you get cached results after you select a different language, I think you should clear the entire cache:

    LanguageController {
    
        public function switchLang() {
            // Switch language
            ResponseCache::clear();
        }
    
    }
    

    Also, seems like spatie/laravel-responsecache allows you to delete specific URIs with ResponseCache::forget('/some-uri');

    To delete cache after altering your data, do something like this

    PostController {
    
        public function index()
        {
            // Display list of posts
        }
    
        public function edit()
        {
            // Display form to edit post
        }
    
        public function update()
        {
            // Delete related cache here and update post
            ResponseCache::forget('/posts');
        }
    }