Laravel middleware redirection using csv file and caching

Laravel Cache CSV Laravel Middleware Laravel middleware redirection using csv file and caching

Learn how to simplify your Laravel development workflow by implementing a powerful middleware solution that utilizes CSV files and caching for dynamic redirects. This technique offers flexibility, performance, and ease of management.

CSV File

Creating csv file with redirects. First column is url from without domain name. Second column is url to.

/wrong-url-1,https://site.com/new-url-1
/wrong-url-2,https://site.com/new-url-2
/wrong-url-3,https://site.com/new-url-3

Kernel.php

Add to app\Http\Kernel.php a new Middleware Class RedirectCustom

protected $middlewareGroups = [
    'web' => [
        ...
        \App\Http\Middleware\RedirectCustom::class
        ...
    ],

    'api' => [
        ...
    ],
];

RedirectCustom Middleware Class

Create RedirectCustom Middleware Class

<?php

namespace App\Http\Middleware;

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

class RedirectCustom
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // CSV file path
        $csvPath = 'storage/urls.csv';
    
        // Request string without GET arguments 
        $url = $request->getRequestUri();
        
        // Get csv file
        $redirects = Cache::rememberForever('redirects', function () use ($csvPath) {
            $csv = fopen(, 'r');
            $lines = [];
            while (!feof($csv) ) {
                $lines[] = fgetcsv($csv, 1000, ',');
            }
            fclose($csv);     
            
            return $lines;          
        });            

        // Search url
        foreach ($redirects as $redirect) {
            if ($url == $redirect[0]) {
                // Doing Redirect Things)
                header("Location: " . $redirect[1], TRUE, 301);
                exit();    
            }        
        }        

        return $next($request);
    }
}

RedirectCustom Middleware Class Workflow

  • Copy data form csv file to array and save it in cache with key 'redirects'
  • Search the array for a match at the url