How to use the clear cache command in the Laravel controller

Clearing cache is required many times during application development. For example, while testing, and making changes, clearing cache avoids the affect of previous implementation. In this tutorial, we are going to learn how to clear route cache, Laravel application cache, config cache in a Laravel 8 application inside a controller using with out artisan command-line interface.

public function clearAllCache() {

    Artisan::call('route:cache');
    Artisan::call('config:cache');
    Artisan::call('cache:clear');
    Artisan::call('view:clear');

    return 'Route, Configuration and View cache has clear successfully!';
}

We can clear cache from a Laravel application in many ways without the CLI.

Laravel Controller provides a space to call Artisan commands outside the CLI.

The call method can be used in a Laravel controller to call other commands from an existing Artisan command. The method works like a CLI interface. Therefore, it accepts a command name and an array of the command parameters.

The example above for the function clearAllCache() passes the command names to clear route, config, cache, and view data. However, no parameter is passed here. As it directs to clear all information.

In some cases, we [pass commands like email: send, as shown below. This is to send an email to a specific user. Therefore, we pass the specific user as a parameter here.

$this->call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

The methods above show how to use Artisan commands like the clear cache command in Laravel controller. To perform various function from the controller method and avoid using the CLI.

Leave a Comment