Is it possible to change the request before processing the route file in Laravel?

Is it possible to change the request before processing the route file?

Basically the application I'm looking for to create will contain hundreds of urls for slug. But the bullets will lead to different controllers. For this, I will hold the key: pairs of values ​​in redis.

For instance:

// 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 change the query in the previous filter in filters.php

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

Hope you can advise.

+4
source share
1 answer

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

One way would be to define a route like this:

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

Then inside slugRedirect you search on redis, then call (or redirect from 301) the correct controller as follows:

 // 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 have not tested this, please let me know if it works or not.

+3
source

Source: https://habr.com/ru/post/1498143/


All Articles