【问题标题】:Is it possible to remove request query parameters from URL? Laravel是否可以从 URL 中删除请求查询参数?拉拉维尔
【发布时间】:2021-08-20 14:51:26
【问题描述】:

我有一个使用 {!! Form::open(['method' => 'GET']) !!} 和不同查询字段的 laravel 查询表单。

例如,我有类似的字段

  • 姓名
  • 类别
  • 价格

用户根据需要填写字段,但是,即使字段为“空白”(null),查询参数也会出现在 URL 中 例如 sitename.com/products?name='test'&category=&price=

我想知道是否有删除任何空参数的方法?

我尝试将array_filter() 添加到我的返回变量

$query->paginate(24)->appends($request->query()) 这样就可以了

$query->paginate(24)->appends(array_filter($request->query())) 但是这不会影响 URL。

使用示例的请求的一些代码是:

$query = Product::with('image')->visible(1); // visible is a custom attribute

if($request->get('name')) $query->where(function($query) use ($request) {
   $query->where('products.name', 'LIKE', '%' . $request->get('name') . '%')
   ->orWhere('products.slug', 'LIKE', '%' . $request->get('name') . '%');
     });

return view('browse.products', [
  'products' => $query->paginate(24)->appends($request->query())
]);

【问题讨论】:

  • 浏览器负责在您提交表单后制作请求。您可以 (1) 有一个提交处理程序,它停止默认浏览器行为并使用例如window.location.href = ... 以您希望的方式重定向 (2) 创建一个服务器端重定向,如果存在空查询参数,则删除它们。

标签: php mysql laravel laravel-8 php-7.4


【解决方案1】:

你可以试试这个

{{ Form::open(array('url' => route('get.index') . '?' . Request::server('QUERY_STRING'), 'method' => 'get')) }}

【讨论】:

  • 嗨!我刚才试过这个方法,它仍然返回带有空参数的字符串,当我@dd Request::server('QUERY_STRING')时,它返回name='test'&category=&price=
  • 在编辑路线名称后尝试代码,如答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2019-06-15
  • 2018-01-01
  • 2022-10-02
相关资源
最近更新 更多