Laravel Website Optimize using Middleware

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Laravel Website Optimize tutorial, I will show how to optimize your website. In this tutorial, We are going to learn how to optimize laravel applications using middleware. First, you have to knowledge about what is middleware?

What is Middleware?

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. We can use middleware in any task. Today we will show that how to cache websites using middleware. If you don’t know how to cache a database in laravel application read this blog.

Read More: Laravel Website Optimize using Cache

Well, Let’s create a middleware by this command. Copy this command and hit your terminal.

php artisan make:middleware CacheResponseMiddleware

Well, your middleware has been created. you can see it app/Http/Middleware folder. Now you have to register this middleware in the Kernel. This is Http kernel which is in located this namespace namespace App\Http;

Well, to register this middleware goes to the Kernel class. Inside the routeMiddleware array, you have to register your custom middleware.

 protected $routeMiddleware = [
        'cache_response' =>        \App\Http\Middleware\CacheResponseMiddleware::class,
    ];

Well, now time to write code in the middleware. Open your middleware class file which you have created before.

By default, a middleware has a handle method where you have to define your logic. But in this middleware, we need to do some work after the HTTP response has been sent to the browser. So we need another method which is terminate. Follow below code

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CacheResponseMiddleware
{
    private $time;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $ttl = null)
    {
        $this->time = $ttl ?? now()->addDay();

        if (Cache::has($this->cacheKey($request))) {
            return response(Cache::get($this->cacheKey($request)));
        }


        return $next($request);
    }

    public function terminate($request, $response)
    {
        if (Cache::has($this->cacheKey($request))) {
            return;
        }
        Cache::put($this->cacheKey($request), $response->getContent(), 5);
    }


    private function cacheKey($request): string
    {
        return md5($request->fullUrl() . '-' . auth()->id());
    }
}

Well, now I will explain what I am doing in this middleware class. First look handle method, this handle method takes three parameters. The first two-parameter you have o define must last parameter is optional. Using the last parameter we send a dynamic value when we will use this middleware. Clearly say it denoted time.

Even if ttl value is equal to null then the time value will today. You may notice that I have made a method cacheKey that returns a unique key by request URL and auth id.

You can use this middleware like this.

Route::get('response-cache', function () {
    $products = Product::with('user')->latest()->get();
    return view('cache', compact('products'));
})->middleware(['auth', 'cache_response:10']);

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m 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: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

Leave a Reply

Your email address will not be published. Required fields are marked *