Laravel 5.4:使用参数从控制器调用路由函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45133885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:18:27  来源:igfitidea点击:

Laravel 5.4: call a route function from controller with parameters

phplaravellaravel-5routes

提问by Ajmal Razeel

I want to call a route function from my controller with some parameters.

我想用一些参数从我的控制器调用路由函数。

This is my Controller

这是我的控制器

public function myFunction($id, $name)
{
    $id = 1;
    $name = 'john';

    return redirect()->route('details/' . $id . '/' . $name);
}

This is my route

这是我的路线

Route::get('details/{id}/{name}',['uses' =>'My_controller@myFunction']);

This is the error I get when I run the script.

这是我运行脚本时得到的错误。

InvalidArgumentException in UrlGenerator.php line 304:

Route [details/1/john] not defined.

Please Help

请帮忙

回答by verax

route()helper requires you to pass route name and parameters:

route()helper 要求您传递路由名称和参数:

function route($name, $parameters = [], $absolute = true)
{
    return app('url')->route($name, $parameters, $absolute);
}

So you need to give your route a name:

所以你需要给你的路线一个名字:

Route::get('details/{id}/{name}',['uses' =>'My_controller@myFunction'])->name('details');

..and then you can pass parameters in an array:

..然后你可以在数组中传递参数:

return redirect()->route('details', array('id' => $id, 'name' => $name));

Hope this helps

希望这可以帮助