'Laravel: Clear selected cache only

Laravel version: 7.x / Cache driver: File.

I have several modules with load-more pagination. Each page is cached for 1 day with the unique key for every logged in user, such as (user_id:1/2/3/... + module:products + page:index + page_number:1/2/3/...).

But, the problem arises when the user creates a new record or makes any change in an existing one. As the pages are cached, the new changes and new records are not reflected until the next day. To overcome this issue, I am forced to run Artisan::call('cache:clear'); in store, update and delete method of every controller (which is kind of killing the cache concept at all).

I need a way to clear the cache for all the pages in products module and for the respected user only.



Solution 1:[1]

I am not sure whether this is the right way or not. But, the following code solved my problem:

use App\Models\SomeModel;

class SomeController extends Controller
{
    public function store/update/delete/etc...()
    {
        ...

        $this->__clearCache(new SomeModel);
    }
}
class Controller extends BaseController
{
    /**
     * Clear all the cache for this module
     *
     * @param   object  $ModelClass
     * @return  null
     */
    protected function __clearCache(object $ModelClass)
    {
        $Model = $ModelClass->_clearCache();
        $cache = strtoupper(Str::singular($ModelClass->getTable()));

        foreach ($Model['model'] as $item)
        {
            cache()->forget("{$cache}.SHOW.{$item['id']}");
        }


        for ($page = 1; $page <= ceil($Model['count'] / RECORDS_PER_PAGE); $page++)
        {
            cache()->forget("{$cache}.INDEX.{$page}");
        }

        return null;        
    }
}
trait ClearCache
{
    /**
     * Fetch records to calculate and 
     * clear the cache
     *
     * @return  array
     */
    public function _clearCache(): array
    {
        $Self = self::select('id')->get();

        return ($Self->isNotEmpty()) ? [
            'count' => $Self->count(),
            'model' => $Self->toArray(),
        ] : [];
    }
}
use App\Http\Traits\ClearCache;

class SomeModel extends Model
{
    use ClearCache;

    ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1