【问题标题】:Laravel redirect from controller gives "method is not supported for this route" error来自控制器的 Laravel 重定向给出“此路由不支持方法”错误
【发布时间】:2020-08-23 22:09:31
【问题描述】:

我有一条支持 PUT 的路由:

Route::put('/products/{id}/cancel/', 'ProductController@cancel')->where('id', '[0-9]+');


Controller 更新产品的状态后,它应该重定向到另一个路由:

return redirect('products')->with('success', 'Produto cancelado');

指向

Route::get('/products', 'ProductController@list')->name('products');


在重定向之前一切正常。 产品已更新,但重定向给出方法不受支持的错误:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
The PUT method is not supported for this route. Supported methods: GET, HEAD


我还尝试了以下重定向:

return redirect('/products/')->with('success', 'Produto cancelado');

return redirect()->route('products')->with('success', 'Produto cancelado');


PUT 方法是如何传递的?我应该在重定向中显式调用 GET 方法吗?

我应该如何解决这个问题?


编辑: 我正在从 HTTP 请求发送 PUT。所以我要回到 JS 函数。我想转发一个接受 with-> 的视图。


编辑2: 我可以返回一个视图,但它只出现在网络>开发者工具的预览中。

return view('pages.products')->with('success', 'Produto cancelado');

但我显然需要它在窗口中。

我可以在 js 中重定向,但这样我会错过在部分刀片中显示 flash 消息。


我不知道该怎么办。

谢谢

【问题讨论】:

    标签: laravel redirect methods routes put


    【解决方案1】:

    错误不在 GET 方法中。错误说不支持 put 方法

    Route::put('/products/{id}/cancel/', 'ProductController@cancel')->where('id', '[0-9]+');
    

    如果您尝试使用domainname.com/products/5/cancel,则如下定义。

    Route::get('products/{id}/cancel', 'ProductController@cancel')->where('id', '[0-9]+');
    

    【讨论】:

    • 我想让 PUT 到达 @cancel。这是正确的并且工作正常。我还希望 GET 访问“产品”。我不知道为什么它在重定向到 GET 时使用 PUT
    【解决方案2】:

    我最终做了一些作弊:


    我添加了一条新的 PUT 路由:

    Route::put('/products', 'ProductController@list')->name('products_put');
    


    控制器返回:

    return redirect()->route('products')->with('success', 'Produto cancelado',200);
    


    并且响应处理程序进行作弊:

    document.write(this.responseText);
    window.history.pushState('products', 'eBaw · online shopping', '/products');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2020-05-15
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2021-03-12
      • 2020-12-05
      • 2021-04-11
      相关资源
      最近更新 更多