Laravel Improve Speed Performance Using Model Caching Tutorial With Example

How to reduce 1 or more queries in one page to 0 (zero) queries? In this example, I will explain to you how to do Laravel Improve Speed Performance Using Model Caching Tutorial With Example. In this tutorial, we will use the laravel model caching library. This great library allows to fully cache entire eloquent objects and reduce queries to 0.

Where to use model caching?

If you have a menu on each page, complex form with many drop-downs populated from database, lot data loaded in the background (Language, Time Format, Date Format, Dictionaries, etc.) Cache it.

Laravel Improve Speed Performance Using Model Caching Tutorial With Example

We are going to Configure Laravel Project.

#1: Install Laravel Project

Install Laravel 5.6 Project by the typing following command.

$ composer create-project --prefer-dist laravel/laravel laravelmodelcaching

#2: Install DebugBar

Next, cd into the project and install DebugBar. Use artisan composer command to download libs.

composer require barryvdh/laravel-debugbar --dev

Then you can publish vendor by the following command:

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

#3: Install Model Caching Package

Now we will install genealabs/laravel-model-caching composer package using by following command in our project.

composer require genealabs/laravel-model-caching

#4: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelmodelcaching
DB_USERNAME=root
DB_PASSWORD=

Now migrate table by the following command.

php artisan migrate

#5: Create Dummy Users

Next, we will create dummy users record using the factory. so you can run below command to create dummy users in your database.

php artisan tinker

factory(App\User::class, 50)->create();

You can see database records in below screenshot.

Laravel Model Caching - Boost Speed Example

#6: Create one controller

php artisan make:controller ModelCacheController

It will build the controller file called ModelCacheController.php.

// ModelCacheController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class ModelCacheController extends Controller
{
    public function index()
    {
        $users = User::all();
        return view('user',compact('users'));
    }
}

#7: Define Route

We register all route in a web.php file.

Route::get('users', 'ModelCacheController@index');

#8: Create a View File

You can create a file in resources/views/user.blade.php and put this following code in it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Laravel Improve Speed Performance Using Model Caching Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2>Laravel Improve Speed Performance Using Model Caching Tutorial With Example</h2><br/>
	    <table class="table table-bordered">
		    <tr>
			    <th>Id</th>
			    <th>name</th>
			    <th>email</th>
		    </tr>
		    @foreach($users as $user)
		    <tr>
			    <td>{{ $user->id }}</td>
			    <td>{{ $user->name }}</td>
			    <td>{{ $user->email }}</td>
		    </tr>
		    @endforeach
	    </table>
    </div>
  </body>
</html>

#9: Testing

php artisan serve

Now, what will happen when you will load localhost:8000/users in the browser?

Laravel Improve Speed Performance Using Model Caching Example

What is happening? Because laravel uses “lazy load” approach page is generating 1 query.

#10: Update User Model

What I did. I added Cachable trait — with this all data from the database will be stored in a cache. Now if you will run again your project you will see 0 database query.

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;


class User extends Authenticatable
{
    use Notifiable;
    use Cachable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Laravel Improve Speed Performance Using Model Caching Tutorial

At last, our Laravel Improve Speed Performance Using Model Caching Tutorial With Example is over.

Post Your Thoughts

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