【问题标题】:Laravel redirect to controller action with Request objectLaravel 使用 Request 对象重定向到控制器操作
【发布时间】:2018-10-11 13:52:21
【问题描述】:

在 Laravel 5.6 应用程序中,我有一个控制器来管理产品树。 getTree() 方法正在从数据库构建树,updateTree() 修改它。这两种方法都是通过 ajax 接受请求参数来调用的:

刀片:

$.get("{{ URL::to('api/gettree') }}", {
  data: $("#data").val()
  }, function(response) { ... });

$.post("{{ URL::to('api/updatetree') }}", {
  data: $("#data").val()
  }, function(response) { ... });

路线:

Route::get("/gettree", "TreeController@getTree");
Route::post("/updatetree", "TreeController@updateTree");

控制器:

class TreeController extends Controller
{
  public function updateTree(Request $request)
  {
    ... process $request->input() ...
    return redirect()->action("TreeController@getTree");
  }

  public function getTree(Request $request)
  {
    ...
    return view("admin.partials.itemtree", compact("data"));
  }
...
}

我想要实现的是在 updateTree() 运行后通过重定向到控制器操作来触发 getTree() 方法,但是这样我无法传递 getTree() 预期的请求对象。你会怎么做?预先感谢!

【问题讨论】:

    标签: php ajax laravel redirect


    【解决方案1】:

    如果您查看action 方法的signature,则第二个参数用于参数。

    所以你可以像这样传递参数:

    return redirect()->action("TreeController@getTree", [$request]);
    

    或者,您可以从您的 getTree 方法中删除 Request $request 参数,并使用类似 $request = request() 的东西

    【讨论】:

    • 谢谢帕拉斯,它运作良好!我应该自己想出来的。
    • 但是,如果你想传递一个数组作为参数,你应该在调用中省略 [ ] ,否则你会有一个错误异常“数组到字符串转换”。
    • 我认为@Malvolio 并非如此。即使您想将数组作为第一个参数传递,我认为您仍然需要将其包装在一个数组中,因为它充当参数数组,第一个参数作为数组。如果您愿意,可以查看它
    • 我已经这样检查过了: public function methodOne() { $param = ["key" => "value"]; return redirect()->action("Controller@methodTwo", $param); } public function methodTwo(Request $request) { return $request->input();如果我在重定向中将 $param 放在括号中,我会收到“数组到字符串转换”错误。
    • methodTwo 收到 $request 而不是字符串。我不明白这个例子
    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 2013-11-30
    • 2013-05-04
    • 1970-01-01
    相关资源
    最近更新 更多