问题
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