如何将路由中的参数传递给控制器​​?

时间:2017-08-02 12:52:16

标签: laravel

我正在尝试重构我的代码。如果我可以将路由页面中的参数传递给函数所在的控制器,那么我可以重构许多几乎完全相同的函数。

在路由器中这样的东西:

Route::get('/entrepreneurs', 'HomeController@show')->withParameter('enterpreneur');

在Controller中我给出了类似的内容:

public function entrepreneurs($withParameter){
   $entrepreneurs = DB::table('stars')->where('type', '=', $withParameter)->get();

   return view('entrepreneurs', [
     'entrepreneurs' => $entrepreneurs,
   ]);
 }

这可能吗?

--------更新--------

有些人建议我使用路线参数:

Route::get('/entrepreneurs/{paramName}', 'HomeController@show');

但是,我已经使用Route Model Binding来访问各个页面(例如www.mywebsite.com/entrepreneurs/Mark_Zuckerberg)

所以这与你们提供的解决方案相冲突!

4 个答案:

答案 0 :(得分:1)

路线:

Route::get('/entrepreneurs/{enterpreneur}', 'HomeController@show');

HomeController.php:

public function show($enterpreneur = "") 
{
   $entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();

   return view('entrepreneurs', [
     'entrepreneurs' => $entrepreneurs,
   ]);

}

传递静态变量和路径

Route::get('/entrepreneurs', 'HomeController@show')->defaults('enterpreneur', 'value');

并在控制器中以

的形式访问它们
public function show(Request $request) 
{
    $entrepreneur = $request->route('entrepreneur');
    $entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();

    return view('entrepreneurs', [
      'entrepreneurs' => $entrepreneurs,
    ]);

}

https://laravel.com/docs/5.4/routing#route-parameters

答案 1 :(得分:1)

你也可以这样做:

// --------------- routes ---------------------

Route::get("page", [
    "uses" => 'HomeController@show',
    "entrepreneurs" => "value"
]);

// -------------- controller -------------------

public function show(Request $request)
{
    $entrepreneurs = DB::table('stars')->where('type', '=', $request->route()->getAction()["entrepreneurs"])->get();

    return view('entrepreneurs', [
        'entrepreneurs' => $entrepreneurs,
    ]);
}

答案 2 :(得分:0)

我想你可以试试这个:

Route::get('/entrepreneurs/{enterpreneur}', 'HomeController@show');

public function entrepreneurs($enterpreneur){
  $entrepreneurs = DB::table('stars')->where('type', '=', $enterpreneur)->get();

  return view('entrepreneurs', [
   'entrepreneurs' => $entrepreneurs,
  ]);
}

希望对你有所帮助!!!

答案 3 :(得分:0)

如果你想在路线中传递参数

Route::get('/entrepreneurs/type/{paramName}', 'HomeController@show');

对于一个选择性的参数:

Route::get('/entrepreneurs/type/{paramName?}', 'HomeController@show');

使用optionnal paramater,它应该在你的控制器中看起来像这样:

public function show($paramName = null){
   $entrepreneurs = DB::table('stars')->where('type', '=', $paramName)->get();

   return view('entrepreneurs', [
     'entrepreneurs' => $entrepreneurs,
   ]);
 }

您可以在此处获得更多信息:https://laravel.com/docs/5.4/routing#route-parameters