Search code examples
phplaravellaravel-middleware

how to redirect properly using a global middleware in Laravel?


I created a custom middleware to redirect short urls to other urls, I have a Url model that has this information:

{
"id":1,
"original_url":"http://www.google.com",
"short_url":"http://127.0.0.1:8000/wGjxw",
"updated_at":"2023-02-08T21:05:39.000000Z",
"created_at":"2023-02-08T21:05:39.000000Z"
}

so I have created a middleware:

<?php

namespace App\Http\Middleware;

use App\Models\Url;
use Closure;
use Illuminate\Http\Request;

class RedirectMiddleware
{
  
    public function handle(Request $request, Closure $next)
    {     
        //dd('here'); // is not reaching this code
        $url = Url::where('short_url', $request->fullUrl())->first();                     
        if ($url) {             
            return response()->redirectTo($url->original_url);    
        }
        return $next($request);
        
    }
}

app/Http/Kernel.php

....
....

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\RedirectMiddleware::class,

...
...

But, when I hit the url http://127.0.0.1:8000/wGjxw I get a 404 error, This is the web.php

Route::get('/', function () {
    return view('main');
});

Route::post('/urls', [UrlsController::class, 'store'] );

These routes are for showing the page with the form, and for creating the short url and those are working properly, the problem is that it looks like the middleware is not registered or I don't know what is happening, what I want is the short_url gets redirected to the original_url, what can I do? thanks


Solution

  • My error was that the middleware was in the $middlewareGroups property, and it should be in the $middleware property, now it is working properly