Cara menggunakan php cache variable

Cara menggunakan php cache variable

Caching is vital in optimizing your web apps’ performance as it speeds up the website and reduces loading times.

In most cases, when clients demand better website speed, developers often opt for advanced Laravel caching tools to speed up the apps. 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.

What Is Laravel Caching

Laravel gives a strong and easy-to-use execution of caching and distinctive caching backends. With Laravel cache, you’ll efficiently and effectively switch between numerous caching engines without writing any code.. This will combine all of the configuration options for your application into a single file which can be quickly loaded by the framework.

Laravel gives a unified API for different caching frameworks. The cache configuration is located at app/config/cache. php . In this file you’ll specify which cache driver you’d like to use by default throughout your application. Laravel supports prevalent caching backends like Memcached and Redis out of the box.

automatically caches the blade templates, parsing the format into pure php and html format view files, but will still inquire the information for each request.

Why Caching Is Important

A cache’s primary purpose is to extend data recovery performance by reducing the need to get to the basic slower storage layer. Trading off capacity for speed, a cache ordinarily stores a subset of information transitorily, in differentiating from databases whose information is usually total and durable.

Caching data is vital since it makes a significant difference to speed up application execution and increase productivity. It stores data locally, which implies browsers and websites will load speedier since getting to elements such as homepage pictures have already been downloaded.

Clearing your cache on Android can free up important space and resolve issues along with your phone’s battery, speed, and security. Old cached data can degenerate, causing bigger execution issues. In case a specific app gets an upgrade, the cached data from a past version can cause conflict

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 ensure 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.

Nothing as Easy as Deploying Laravel Apps on Cloud

With Cloudways, you can have your Laravel apps up and running on managed cloud servers in just a few minutes.

Laravel provides an efficient and effective API for different caching backends. You can find the configuration for Laravel cache 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.

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 indicating the incremented 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');

Clear Laravel Cache

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.).

Cara menggunakan php cache variable

Cara menggunakan php cache variable

Cara menggunakan php cache variable

Get Ready for Core Web Vitals Update

Ebook to Speed Up Your Website Before You Start Losing Traffic.

Thank You

Your list is on it’s Way to Your Inbox.

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.

Cara menggunakan php cache variable

For the purpose of this tutorial, I have launched my application on the 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

Cara menggunakan php cache variable

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

Cara menggunakan php cache variable
Cara menggunakan php cache variable

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

Cara menggunakan php cache variable

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

Cara menggunakan php cache variable

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

Cara menggunakan php cache variable

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', '[email protected]');

});

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);

}

}

Cara menggunakan php cache variable

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.

Cara menggunakan php cache variable

Redis

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

Cara menggunakan php cache variable

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.

Cara menggunakan php cache variable

Cara menggunakan php cache variable

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.

Q: How to reset Laravel cache?

A: To clear cache in Laravel applications, open your terminal and write the following command:
$ php artisan cache:clear
To clear route cache of your Laravel application, execute the following command:
$ php artisan route:clear
Similarly, to clear config cache of the Laravel application, use the following command:
$ php artisan config:clear

Q: How to resolve “Laravel failed to clear cache” error?

A: This error mostly appears when the data path does not exists under the storage/framework/cache/data directory. To resolve this error, simple create data directory manually under the storage/framework/cache directory.

Q: How to disable Laravel cache?

A: To disable Laravel cache, simple use the following command in your .env file:
CACHE_EXPIRE=-1

Q: Does Laravel cache queries?

A: Yes, you can cache queries in Laravel using a very simple chained method call:
$users = DB::table(‘users’)
->orderBy(‘latest_activity’, ‘desc’)
->take(10)
->remember(60)
->get();

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 Redis’s complete integration in Laravel and 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

Customer Review at

Cara menggunakan php cache variable

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

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 [email protected]