Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Integrate Laravel Cache & Skyrocket Your Web App Performance

February 28, 2019

8 Min Read
laravel cache
Reading Time: 8 minutes

Caching plays a vital role in optimizing the performance of your web apps, because it speeds up website and makes page load time faster than the conventional ones. In most cases, when clients ask about better website speed, developers more than often opt for advanced Laravel caching tools to speed up the apps. No doubt, Laravel cache plays an important role in making a web app’s performance skyrocket.

Recently, I had developed a Laravel-powered web application. During the development process, there wasn’t any major performance issue, but as soon as the project was live and traffic started coming in, its performance went down drastically. Therefore, to solve this derailing performance issue, I used a Laravel caching tool that really did wonders for the app.

In this article, I will demonstrate how to use various caching methods in Laravel.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • PHP 7.1
  • MySQL

To make sure that I don’t get distracted by server level issues, I decided to deploy my Laravel app on Cloudways managed hosting platform. Because it not only assist users how to host Laravel projects in quick steps, but also takes care of server level issues, and offers a great devstack to take advantage of. You can try out Cloudways for free by signing for an account.

Laravel Cache

Laravel provides an efficient and effective API for different caching backends. You can find the configuration for caching within config/cache.php folder.

Inside the file, you can specify which cache driver you wish to use as a default one. Some of the popular Laravel caching backends are:

  1. Memcached
  2. Redis
  3. Database
  4. File
  5. Array

To change the cache driver, simply open the .env file and edit the Cache_Driver = file.

Powerful Laravel Hosting For All Your Needs

Grow your Laravel app with our feature-rich managed hosting

Laravel Cache Usage

To enable Laravel caching services, first use the Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository, as they provide access to the Laravel caching services.

The Factory contract gives access to all the cache drivers of your application. Meanwhile the repository contract implements the default cache driver for your web application.

Laravel Cache has different functions such as

  • Cache::Put ()
  • Cache::Get()
  • Cache::Forever()
  • Cache::Has()

Store Cache

Cache :: Put()i takes three parameter keys, values and time in minutes to cache the entire application data. For testing purposes, you can paste the following code in your routes:

Cache ::put(key, value , 15);

Basically, the key is a unique cache identifier that you can use to retrieve it when you need the data. You can also use remember() method to automate the cache updating process. This method first checks the key, if found, it returns it with the true result. Otherwise, it creates a new key with the value. Check the following code.

Cache::remember('articles', 15, function() {

   return Article::all();

});

The given value, ‘15’ is the total number of minutes to be cached. By using this, you don’t have to bother about checking the cache every time. Instead, Laravel will do that for you and will retrieve the cache automatically every time.

Cache Retrieve

If you have stored your data somewhere, and would like to retrieve it, you can use the Get() method. Just copy and paste the following code in your routes file:

Route::get('/', function()

{

return Cache::get( 'key' );

});

Incrementing / Decrementing Values

To adjust the values of cache integer items, you can use the increment and decrement methods. Both of these methods accept an optional argument that indicates the incremented amount or decremented amount.

Cache::increment('key');

Cache::increment('key', $amount);

Cache::decrement('key');

Cache::decrement('key', $amount);

Existence Cache:: Has()

If you want to check whether the key exists or not before retrieving data, use Has() as defined below:

Route::get('/', function()

{

if (Cache::has('key')){

   Cache::get('key');

} else {

   Cache::put('key', $values, 20);

}});

Remove Cache Value

To clear Laravel cache, simply use the forget() function as shown below:

Cache::forget('key');

You can also retrieve a cache value and can delete it immediately. Technically, you can call it one time caching.

$articles = Cache::pull('key');

You can also clear Laravel cache even before it expires from the console using:

php artisan cache:clear

Clear route cache

To clear route cache of your Laravel application issue below command from terminal.

php artisan route:cache

Clear config cache

To clear config cache of your Laravel application issue below command from terminal.

php artisan config:cache

Clear compiled view files

To clear compiled view files of your Laravel application issue below command from terminal.

php artisan view:clear

Database Cache

When using the Laravel database cache driver, you will need to setup a table to contain the Laravel caching items. You’ll find an example Schema declaration for the table below:

Schema::create('cache', function ($table) {

   $table->string('key')->unique();

   $table->text('value');

   $table->integer('expiration');

});

Why Cloudways?

Cloudways allows easy access to Laravel and other packages in just 1-click. You can install Laravel and some cache configuration tools with your single click.

Furthermore, Cloudways provides an optimized stack of tools including Nginx, Laravel Varnish, Memcached, Apache HTTP accelerator, PHP 7.x, MySQL 5.5 and many others that help optimizing app performance. Apart from this, you can also add advanced scripts to the app without any external configurations (Redis cache, Elasticsearch etc.).

Use Laravel Cache on Cloudways

To demonstrate the outcome of cache in relation to the performance of a Laravel web application, I have implemented Laravel cache on the Cloudways managed hosting platform. I have first installed a new Laravel application through 1-click quick installation process.

For the app deployment, you can always choose your desired cloud server like AWS, Digital Ocean, Linode, and Vultr for the job.

For the purpose of this tutorial, I have launched my application on Digital Ocean cloud server.

For Model and Migration

After successful installation, it is time to create model and migration by pasting the following code:

php artisan make:model Employee-m

Next, open the migration folder, employee migration file and paste the code mentioned below.

public function up() {

   Schema::create('articles', function (Blueprint $table) {

       $table->increments('id');

      $table->string("emp_name");

       $table->string("emp_details");

       $table->timestamps();

   });

}

After setting up migration fields successfully, run the migration command as follows:

PHP artisan migrate

Database Seeding

Now the next step is to seed the ‘articles’ table. To do that, open the database/seeds/DatabaseSeeder.php file and update the Run() code:

<?php

use Illuminate\Database\Seeder;

use Illuminate\Support\Facades\DB;

use App\Employee;

use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder

{

   /**

    * Seed the application's database.

    *

    * @return void

    */

   public function run()

   {

   $faker = Faker::create();

   foreach(range(1, 30) as $index) {

       Employee::create([

           'emp_name' => $faker->sentence(5),

           'emp_deatils' => $faker->paragraph(6)

       ]);

   }

   }

}

The Faker library in Laravel generates fake demo data for the testing purpose. For now, I am using PHP range() method to generate 30 columns of demo data. Just copy and paste the following command to seed the data into the fields.

Php artisan db:seed

Now, open Cloudways database manager, where you will see dozens of tables filled with fake demo data.

Controller

Now, create a controller that will process the requests and caching as per your requirements. Just copy and paste the following command:

php artisan make:controller EmployeeController

Route

Now, add a route in the app/Http/routes.php file which will point to the controller’s index method:

Route::group(['prefix' => 'api'], function() {

   Route::get('employee', 'EmployeeController@index');

});

Testing Without Laravel Cache

Now the application is ready, but not integrated with Laravel caching as of yet. For now, let’s test the application without Laravel cache using POSTMAN:

Let’s open the Employeecontroller file and paste the following code in index() function.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Employee;

class EmployeeController extends Controller

{

   //

public function index() {

   $employee= Employee::all();

//dd($employee);

   return response()->json($employee);

}

}

You can see the screenshot above which clearly shows that without having Laravel cache in the app, the time taken to complete the request is approx. 472 ms.

Testing with Laravel Cache

Now, we will integrate Laravel cache and test the application again. You just have to replace the code for index() function.

For this purpose, I have selected Cache = File, and as you can see the time taken to complete the requests is approx. 284 ms, which is quite less from the last value.

Redis

As Cloudways provides 1-click Redis setup, it’s time to test the request with Redis.

 

To integrate Redis in Laravel, first you have to run the command to install predis in your Laravel application. Next, go to the database.php file and change settings according to Redis configuration.

Once done, open the config/cache.php file and change connection => cache to connection => default.

You can also use Laravel memcached by tweaking the .env file. Simply edit the file type Redis to memcached in your Laravel project and that’s it!

You Might Also Like: Learn How to Integrate Memcached in PHP

Laravel Varnish

PHP Varnish is known as a caching HTTP reverse proxy tool. It basically means that instead of web server, Varnish is authorized to listen the HTTP requests once it is installed. When a request comes in first time, it passes on to web server as usual. The webserver after completing its work, passes on the request to the Varnish. Varnish then caches that response and sends back to the website visitors.

So, when the request comes in the next time, they are easily served by the Varnish with the earlier cached responses.

You can use this package to integrate Varnish in Laravel for better website performance.

Final Words

This brings us to the end of this article. In this blog, I have demonstrated in detail how to integrate and install cache in a Laravel application. The Laravel cache helps improve your website speed and augments its performance tremendously.

The article details the complete integration of Redis in Laravel and also demonstrates how to use other tools like Laravel memcached etc.

If you still have some more questions about Laravel caching, feel free to write your comments below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Pardeep Kumar

Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. You can email him at pardeep.kumar@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!