【问题标题】:Dynamic url laravel动态网址 laravel
【发布时间】:2021-04-27 03:59:56
【问题描述】:

我有一个搜索城市地点的应用。

我有这条路线

  Route::get('s/{where}/{places}', 'SearchController@places')->name('search');

搜索控制器

class SearchController extends Controller{

public function places(Request $request, $where, $places)
{   
    $where = $request->where;
 
    if($places == 'places'){
        return view('search.places', ['where' => $where]);
    }else{
         abort('404');
    }
 }
}

我也试过

   ->with()

要搜索的表单提交

 <form action="{{ route('search' ,  ['where', 'places']) }}" method="get">

我得到了这样的东西:

http://localhost/s/where/places?where=Paris

我想要的是

http://localhost/s/paris/places

当它应该替换 url 中的 where 而不是在问号后添加 where 时!

感谢您的帮助

【问题讨论】:

  • 你的方法不对,试试这个{{ route('search' , ['where' =&gt; 'France', 'places' =&gt; 'Paris']) }}
  • 感谢您的评论,但当我提交表单时,链接应该是动态的,如果是法国、巴黎或中国,我不知道!这就是为什么我发送位置,但在控制器中我想将用户更改为提交的城市位置
  • 字段是动态的{{ route('search' , ['where' =&gt; $countey, 'places' =&gt; $city]) }}希望你现在明白
  • 在我没有定义 $countey 或 $city 的表单中?问题出在控制器而不是表单上!感谢您的帮助
  • whereplaces 是可选参数吗?

标签: laravel url routes


【解决方案1】:

根据您设置路线的方式,您需要设置如下:

<form action="{{ route('search' ,  ['where' => 'paris', 'places' => 'places']) }}" method="get">

【讨论】:

  • 天啊,请阅读我想要的最终结果!我不想要任何可以有或没有的预定义!我没有在刀片中定义任何变量来设置位置!我有一个带有自动完成表单的主页我把我想要的城市我在控制器中提交表单当我返回视图时我想要的结果还在url中设置国家或城市名称
  • 根据你创建路由的方式,你需要像上面那样设置 route() 辅助方法,如果没有,那意味着你设置了错误的路由参数。请评论laravel.com/docs/8.x/routing#generating-urls-to-named-routes
  • 请问我应该如何制作具有可选参数的路线?并且可以做这样的事情:当返回视图返回数据时,用城市提交的表单,并更改 url,或者像这样localhost/s/paris/places 将信息添加到 url 或者我必须创建两条路线并且不可能只使用 1 条路线
  • 你设置一个路由为s/{where}/{places},也就是说当你调用这个路由的时候需要传递2个参数(一个是where,一个是places)如果只需要传递where,那么你需要将你的路由设置为s/{where}/places,然后在你的路由助手方法route('search', 'paris'route('search', ['paris'])route('search', ['where' =&gt; 'paris'])中只传递一个参数。
  • 在你的控制器中你不需要做 $request->where,因为你在方法的地方有 $where 变量作为参数 --> public function places(Request $request, $where, $places), $where 将包含 paris in上一个例子。
猜你喜欢
  • 2014-06-08
  • 2012-12-01
  • 2013-11-29
  • 2013-08-17
  • 2012-03-15
  • 2011-01-10
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多