How to clear cache in Laravel without artisan command

In this tutorial, let’s learn how to clear cache in a Laravel Application, using config cache in a Laravel 8 application without the artisan command-line interface.

Sometimes we may wish to execute an Artisan command outside of the CLI. For instance, you may wish to pass an Artisan command from a route or controller. You can use the call method on the Artisan façade to execute this. The call method will accept command name as the first argument, and command parameters as an array in the second argument. The exit code will be returned:

routes/web.php

// clear route cache
Route::get('/clear-route-cache', function () {
    Artisan::call('route:cache');
    return 'Routes cache has clear successfully !';
});

//clear config cache
Route::get('/clear-config-cache', function () {
    Artisan::call('config:cache');
    return 'Config cache has clear successfully !';
});

// clear application cache
Route::get('/clear-app-cache', function () {
    Artisan::call('cache:clear');
    return 'Application cache has clear successfully!';
});

// clear view cache
Route::get('/clear-view-cache', function () {
    Artisan::call('view:clear');
    return 'View cache has clear successfully!';
});

While we are using the queue method on the Artisan façade, we can also queue Artisan commands so they get processed in background by the queue workers. Before you use this method, make sure to configure your queue and are run a queue listener:

Route::get('/foo', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);
 
    //
});

Other ways to clear cache in Laravel

Programmatically removing items from the cache is as easy like we clear the cache via the artisan command. In addition, you can use the cache façade to access the cache or use the cache helper.

cache()->store('redis')->tags('awesome-tag')->flush()

Clearing cached items with the tag awesome-tag is as easy as purging a specific cache store:

Using the code above, you can clear cached items with the tag awesome-tag. The flush() function works here to clear all data matching the string added in the tags function.

The methods above enable clear cache in Laravel without using the CLI or the artisan commands.

Leave a Comment