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

若如初见. 提交于 2019-12-10 16:25:49

问题


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

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.

For example:

// 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');

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";
});

Hope you can advise.


回答1:


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');

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.



来源:https://stackoverflow.com/questions/18351697/is-it-possibly-to-modify-the-request-before-being-processed-by-the-routes-file-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!