是否有可能在Laravel中的路由文件处理之前修改请求? [英] Is it possibly to modify the request before being processed by the routes file in Laravel?

查看:73
本文介绍了是否有可能在Laravel中的路由文件处理之前修改请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在路由文件处理之前修改请求?

Is it possibly to modify the request before being processed by the routes file?

基本上,我要构建的应用程序将具有数百个Slug URL.但是,这些弹头会导致使用不同的控制器.为此,我将key:values对保留在redis中.

Basically the app I am looking to build will have hundreds of slug URLs. But the slugs will lead to different controllers. To achieve this I will keep key:values pairs in redis.

例如:

// slug = domain.com/slug-one
// Would route to
Route::get('pages/{id}', 'PagesController@index');

// slug = domain.com/slug-two
// Would route to
Route::get('articles/{id}', 'ArticlesController@index');

对我来说,最好的方法是在filters.php中的before过滤器中修改请求

For me the best way would be to modify the request in the before filter in filters.php

App::before(function($request)
{
    // Do Redis Lookup.  If match change request path
    $request->path = "$controller/$id";
});

希望您能提供建议.

推荐答案

您无法在过滤器中更改请求路由,因为在解决路由后应用了过滤器.

You can't change a request routes in a filter because filters are applied AFTER the route is resolved.

一种方法是定义一条这样的路线:

One way would be to define a route like that:

Route::get('/{$request}', 'PagesController@slugRedirect');

然后在slugRedirect内部,执行redis查找,然后调用(或使用301重定向)正确的控制器,如下所示:

Then inside the slugRedirect you do your redis lookup then call (or redirect with 301) the correct controller like that:

// Create a new separate request
$request = Request::create('/articles/1', 'GET');
// Dispatch the new request to a new route
$response = Route::dispatch($request);
// Fetch the response (in your case, return it)

我还没有测试过,请告诉我它是否有效.

I haven't tested that, please let me know if it work or not.

这篇关于是否有可能在Laravel中的路由文件处理之前修改请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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