Laravel middleware redirection using database and caching

Laravel Cache CSV Laravel Middleware Laravel middleware redirection using database and caching

Migrations

Creating a table for storing redirects. Also add an additional field for HTTP status

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRedirectsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('redirects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('url_from', 191);
            $table->string('url_to', 191)->nullable();
            $table->smallInteger('status', 191)->unsigned()->default(301);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('redirects');
    }
}

Redirect Model

Creating Redirect Model

<?php

namespace App\Models\Seo;

use Illuminate\Database\Eloquent\Model;

class Redirect extends Model
{
    protected $fillable = [
        'url_from',
        'url_to',
        'status'
    ];
}

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)
    {
        // Request string without GET arguments 
        $url = $request->getRequestUri();
        
        // Get csv 
        $redirects = Cache::rememberForever('redirects', function () use ($csvPath) {           
            return Redirect::all();          
        });            

        // Redirect
        foreach ($redirects as $redirect) {
            //
            if ($redirect->status == 410) {
                header("HTTP/1.1 410 Gone");
                exit();
            }        
        
            if ($url == $redirect->url_from) {
                header("Location: " . $redirect->url_to, TRUE, $redirect->status);
                exit();    
            }        
        }        

        return $next($request);
    }
}

RedirectCustom Middleware Class Workflow

  • Copy data form database table redirects to array and save it in cache with key 'redirects'
  • Search the array for a match at the url
  • Use HTTP status form database for redirect