url-rewritingrouteslaravel-5.1pretty-print

change the get url before laravel 5.1 route intercepts it


After finally mastering crucial parts of Laravel I'm ready to refactor all of my procedural code.

I have one problem, some other program's use the following url's like this:

http://my.domain.com/somecode.php?something=a&somethingelse=b

Now as I learned, laravel route looks like:

http://my.domain.com/somecode/something/a/somethingelse/b

How should I intercept the old style of url in laravel or before the laravel route is called and translate it so the route can handle it?


Solution

  • As long as you will only be doing this with GET you could use middleware to solve your issue.

    Create the middleware

    php artisan make:middleware RedirectIfOldUrl

    ...or whatever you want to call it.

    Add the definition to your app/Http/Kernel.php

    add \App\Http\Middleware\RedirectIfOldUrl::class, to the $middleware array (not the $routeMiddleware) array.

    This will cause the middleware to be called on every request.

    Handle the request

    public function handle($request, Closure $next)
    {
    
        if (str_contains($request->getRequestUri(), '.php?')) {
    
            //Remove .php from the request url
            $url = str_replace('.php', '', $request->url());
    
            foreach ($request->input() as $key => $value) {
    
                $url .= "/{$key}/{$value}";
            }
    
            return redirect($url);
        }
    
        return $next($request);
    }
    

    The above is a very basic implementation or what you mentioned in your question. It is possible that you will need to tweak the logic for this to work exactly right for your application but it should point you in the right direction.

    Hope this helps!