Laravel: Clearing Cache with a click of a button (Artisan Shortcuts)

Published on

Laravel: Clearing Cache with a click of a button (Artisan Shortcuts)
Laravel: Cache

In this tutorial we will learn how to purge compiled views and cache by using Laravel Commands.

Switching back and forth between applications might be cumbersome during development for some folks who have a single monitor. Thanks to the commands in Laravel, we can create and call those commands from anywhere.

Before you begin, keep in mind that you should only use this method for Development purposes. Because purging and re-caching might effect your site's performance

Let's start by creating a controller for our operations like this:

php artisan make:controller DevClearCacheController

 Now add following methods to DevClearCacheController class like this:

namespace App\Controllers;

class DevClearCacheController extends Controller
public function clear_views()
{ \Artisan::call('view:clear');
return redirect()->back()->with('status','Views Cleared!');

public function clear_cache()
return redirect()->back()->with('status','Cache Cleared!');

// you can also add methods for queue:start, queue:restart etc.

 Now let's add these to the web.php file in the routes directory.



Route::get('clear-views', 'DevClearCacheController@clear_views')
Route::get('clear-cache', 'DevClearCacheController@clear_cache')

Now, let's create a view that contains our buttons (I prefer to add these in navbar):

<!DOCTYPE html>
<html lang="{{ App::getLocale() }}">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('', 'Artisan Shortcuts') }}</title>
<link rel="stylesheet" href="">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar">A</span>
<span class="icon-bar">B</span>
<span class="icon-bar">C</span>
<a href="/" class="navbar-brand">{{ config('', 'Artisan Shortcuts') }}</a>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="{{ route('clear-views') }}">Clear Views</a></li>
<li><a href="{{ route('clear-cache') }}">Clear Cache</a></li>
</div><!--/.nav-collapse -->

<div class="body-content">
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
<p>Test App</p>
<!-- Scripts -->
<script src="/js/jquery-1.12.4.min.js"></script>
<script src="/js/jquery.validate.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

 Now let's test our application, the result will be similar to the following: