Improve Speed Performance using Model Caching in Laravel 5

0
1363

There are various factors that affect the speed of an application. Among them, frequent database queries for the repetitive task is one. For these types of task, we can use Model Caching. We will do it for our fresh laravel project. So let’s get started implementing it in our project.

Create Project

We will create a new laravel project for this. Run the artisan command:

composer create-project laravel/laravel laravelmodelcaching

Database Setup

After creating project, we need to setup our database. Lets create a database named modelcaching and do necessary setup in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=modelcaching
DB_USERNAME=root
DB_PASSWORD=secret

Intall Laravel Debugbar

We are installing it to for the debugging purpose only. We will use it only in our development environment. To install it, run the command:

composer require barryvdh/laravel-debugbar --dev

Laravel 5.5 uses Package auto-discovery, so we don’t need to manually add the ServiceProvider.
Then, you can publish the configuration with command below:

php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"

Install Model Caching Package

This is our main package which enables to cache our models. You can find more information about this package in GitHub repository.

To install it, run the command:

composer require genealabs/laravel-model-caching

Create Model & Migration

We will create a customers table and respective model. Run the following command:

php artisan make:model Customer -m

This will create a migration file and a model. We will add some columns in customers table by changing in migration file. So, our migration file looks as below:

// database/migrations/customers migration file
public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name', 100);
        $table->string('last_name', 100);
        $table->date('dob')->nullable();
        $table->string('gender', 10);
        $table->string('address', 100)->nullable();
        $table->string('phone', 100)->nullable();
        $table->timestamps();
    });
}

Similarly, open your Customer model and make necessary changes to fit our migration.

// App/Customer.php

Since, we have already setup our migration, lets migrate our database. Run the command.

php artisan migrate

Database Seeding

We will populate our database using faker package. You don't have to install any package. Laravel comes with this package. First of all let's create a seeder to populate customers table.

php artisan make:seeder CustomersTableSeeder

This will create a seeder file inside database/seeds/. We will populate 50 students.

insert([
                'first_name' => $faker->firstNameMale,
                'last_name'  => $faker->lastName,
                'dob'        => $faker->dateTime,
                'gender'     => 'Male',
                'address'    => $faker->address,
                'phone'      => $faker->phoneNumber,
                'created_at' => $faker->dateTime(),
                'updated_at'  => $faker->dateTime()
            ]);
        }
    }
}

Include this newly created seeder file inide run() function in seeds/DatabaseSeeder file.

public function run()
{
    $this->call(CustomersTableSeeder::class);
}

All setup for seeding. Let's populate database by running command:

php artisan db:seed

Create Route

It's time to register a route in web.php file.

Route::get('customers', 'CustomerController@index');

Create Controller

Lets create a controller file. Run the following command:

php artisan make:controller CustomerController

Open up our controller file and make some necessary changes.

// App/Http/Controllers/CustomerController.php

Create Blade File

We have setup all our project and created routing, controller. Now, let's create view file inside customers directory. Our final blade file looks like below:







Improve Speed Perfomance using Model Caching in Laravel 5






    

Improve Speed Perfomance using Model Caching in Laravel 5


@foreach($customers as $key => $customer) @endforeach
SN First Name Last Name DOB Gender Address Phone
{{ $key }} {{ $customer->first_name }} {{ $customer->last_name }} {{ $customer->dob }} {{ $customer->gender }} {{ $customer->address }} {{ $customer->phone }}

Testing

To test our application, run the project.

php artisan serve

We will test our application in two-phase i.e. firstly without implementing Model Caching and secondly, with model caching.

Testing without Model Caching

Below is a screenshot of result I have tested without using model caching.
Improve Speed Perfomance using Model Caching in Laravel 5

Testing with Model Caching

To implement model caching we need to implement Cachable Trait in our model. Thus, after implementation, our model looks like below:


The above implementation of model caching resulted as below:
Improve Speed Perfomance using Model Caching in Laravel _kodementor

This is all for laravel model caching. I hope you have got a pretty clear idea about implementing model caching in laravel. If you have any question, please leave a comment below. I always appreciate your feedback.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.