Laravel Website Optimize using Cache and Middleware

Spread the love

Laravel Website Optimize is one of the common headaches for new developers. Hello developers. Today we are going to learn how to optimize your laravel application. To optimize we will cache and middleware. Well, first I will show you that how to optimize databases using cache.

Cache In Laravel

Laravel provides an expressive, unified API for various cache backends, allowing you to take advantage of their blazing-fast data retrieval and speed up your web application.

In your application’s cache configuration file is located at config/cache.php. In this file, you may specify which cache driver you would like to be used by default throughout your application. Laravel supports popular caching backends like MemcachedRedisDynamoDB, and relational databases out of the box. In addition, a file-based cache driver is available, while array and “null” cache drivers provide convenient cache backends for your automated tests.

The cache configuration file also contains various other options, which are documented within the file, so make sure to read over these options. By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects on the server’s filesystem. For larger applications, it is recommended that you use a more robust driver such as Memcached or Redis. You may even configure multiple cache configurations for the same driver.

Cache Using Redis

For caching in this tutorial we will Redis. Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker.

First, you have to install Redis in your system. Using the below command you can check Redis has existed or not in your system.

shahin@shahin-bhai:~$ redis-cli 
// Output should be like this> 

Before using a Redis cache with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the predis/predis package (~1.0) via Composer. Run this command in your project’s terminal.

composer require predis/predis

Well, after installing this package then you have to change the cache driver. By default cache driver is the database, you can see it .env file. Change cache driver database to cache.

Read More : Laravel Authorization Gate and Policy with Example

Well, now you have to uncomment Redis class which is commented by default. Go to config/app.php file and uncomment this line of code.

      'Redis' => Illuminate\Support\Facades\Redis::class,

Well, now you have to write code for the cache. In this tutorial, I have cached my products database. Your code looks like.

  $products = Cache::rememberForever('products', function () {
        return Product::with('user')->latest()->get();
    return view('produtcs', compact('products'));

Well, in this code we have cached the product forever. Now I will show you how to add new data in the cache when you are inserting or deleting or updating. You can do it by the event listener or model observes or model’s boot function.

Event and Listener

Let’s create an event and listener for the cache. Using event and listener I will show you how to remove data from the cache when you are deleting data.

php artisan make:event ProductDeleted
php arisan make:listener ProductDeletedListener

Well, now you have to bind this event and listener in EventServiceProvider. Go to the EventServiceProvider and add this code.

 protected $listen = [
        ProductDeleted::class => [

Let’s utilize laravel model events for the cache. Then you have to assign this event in the model.

  protected $dispatchesEvents = [
        'deleted' => ProductDeleted::class

Your listener code will like this.

 public function handle(ProductDeleted $event)

        $products = Product::with('user')->latest()->get();
        cache('products', $products);
Boot Function

When you will create a product then this boot function will be fire.

   protected static function booted()
        static::created(function ($product) {

            $products = Product::with('user')->latest()->get();
            cache('products', $products);

Well, now I will show you how to use Observers for the cache. Let’s create a product observer by this command.

php artisan make:observer ProductObserver --model=Product

Observer gives you a restful class where you can write any logic according to the model event. Now I will show you how to change the cache when a product will update.

    public function updated(Product $product)

        $products = Product::with('user')->latest()->get();
        cache('products', $products);

So when you update a product this update method will fire and change cached Data. Hope this tutorial will help you.

Spread the love

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m an Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website:

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published.