duannao1920 2019-01-28 17:19
浏览 316
已采纳

通过Laravel中间件转发请求

In other frameworks, the concept of request forwarding exists, were a request can be internally redirected to another controller action within the app without responding back to the user with an explicit redirect.

For an ecommerce example, if a product has a SEO-friendly URL of /red-shoes.html, a request to that URL would internally forward to /catalog/product/id/1234. The user would receive a 200 response code and the product page for product ID 1234 would be rendered at the original URL of /red-shoes.html. The behavior I'm trying to avoid is issuing a 301 redirect to /catalog/product/view/id/1234 and losing the friendly URL.

How can this be accomplished in Laravel (5.7)? I can introduce a piece of middleware to intercept the request, but in middleware, I can only redirect within the app. redirect() sends a 302 back to the user, which I don't want.

namespace App\Http\Middleware;

use Closure;
use App\Rewrite;

class ProductForward
{
    public function handle($request, Closure $next)
    {
        // make a lookup to see if URI in request matches a known product
        $productId = Product::lookupRequest($request);
        if ($productId) {  // if matches, forward to product controller
            return redirect()->route('catalog_product', ['id' => $productId]);  // not desired
        }
        // if no match is found, continue on with the request
        return $next($request);
    }
}

As a follow-up, is it possible to execute this lookup after routing has completed, if no route matches?

For example, assume the route /login exists to render the login page. If the user goes to /login, there's no point in looking up a product-friendly URL for this request - just render the login page. But, if the user visits /blue-shoe.html, and that's not a pre-defined route in Laravel, execute the product lookup and forward after app routing but before a 404 is rendered.

  • 写回答

1条回答 默认 最新

  • dongmaqiu6084 2019-01-28 17:49
    关注

    Could SEO-friendly URLs be in a section like products/red-shoes?

    Then you can create a route with parameter like Route::get('products/{seoName}'); that will lead to the same controller you use for handling requests like /catalog/product/view/id/1234. There you can resolve and find out that a controller's action was reached with product's ID or seo-name and show a matching product.

    Basically, you can have two routes products/red-shoes and /catalog/product/view/id/1234 that will show the same page, without redirect.

    Controller action

    Also, you can execute a controller method directly from the middleware.

    Instead of calling

    return redirect()->route('catalog_product', ['id' => $productId]);

    you may run something like

    return app('App\Http\Controllers\ProductController')->show($productId);

    Then you will get a content of a product page without a redirect.

    Fallback route

    To prevent running the middleware on every request you can use a fallback route.

    Route::fallback(function () {
        //
    });
    

    Fallback route will be executed only if a request doesn't match any of registered routes. There you can search for a product and if nothing then return a 404 response.

    So you will get something like this:

    Route::fallback(function ()
    {
        // make a lookup to see if URI in request matches a known product
        $productId = Product::lookupRequest(request());
        if ($productId) {  // if matches, forward to product controller
            return app('App\Http\Controllers\ProductController')->show($productId);
        }
        abort(404);
    }
    

    Fallback route should be registered last in your file.

    More info https://laravel.com/docs/5.7/routing#fallback-routes

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3