在 Laravel 5.1 路由拦截它之前更改 get url [英] change the get url before laravel 5.1 route intercepts it

查看:66
本文介绍了在 Laravel 5.1 路由拦截它之前更改 get url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最终掌握 Laravel 的关键部分后,我准备重构我的所有程序代码.

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

据我所知,laravel 路线如下所示:

Now as I learned, laravel route looks like:

http://my.domain.com/somecode/something/a/别的东西/b

如何在laravel中或者laravel路由调用之前拦截旧样式的url并进行翻译以便路由可以处理?

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?

推荐答案

只要您只使用 GET 执行此操作,您就可以使用中间件来解决您的问题.

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

创建中间件

php artisan make:middleware RedirectIfOldUrl

...或者随便你怎么称呼它.

...or whatever you want to call it.

将定义添加到您的 app/Http/Kernel.php

\App\Http\Middleware\RedirectIfOldUrl::class, 添加到 $middleware 数组(不是 $routeMiddleware)数组.

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.

处理请求

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.

希望这会有所帮助!

这篇关于在 Laravel 5.1 路由拦截它之前更改 get url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆