skip to Main Content

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 AppHttpMiddleware;

use AppModelsUrl;
use Closure;
use IlluminateHttpRequest;

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' => [
            AppHttpMiddlewareRedirectMiddleware::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

2

Answers


  1. Chosen as BEST ANSWER

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


  2. If the middleware approach isn’t working, you could make a route specifically for it using route model binding with short_url as the key.

    https://laravel.com/docs/9.x/routing#customizing-the-key

    Route::get('/{url:short_url}', fn (Url $url) => redirect()->away($url->original_url));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search