存在某些查询字符串时定义Laravel路由 [英] Defining Laravel routes when certain query strings are present
问题描述
说我希望能够在将?s=
附加到当前URL的任何页面上提交搜索表单,但返回SERP:https://example.com/my-page?s=foobar
. (我见过一些站点这样做而不是指向/search?s=.*
-不是我这样做的方法,但这说明了我的问题.)
Say I want to be able to submit a search form on any page that will append a ?s=
to the current url but return a SERP: https://example.com/my-page?s=foobar
. (I've seen a few sites do this instead of pointing to /search?s=.*
- not the way I'd do it, but it illustrates my question.)
在我的Laravel web.php
路线中,除了可能使用不规则的正则表达式外,目前还有其他方法可以注册吗?
In my Laravel web.php
routes, is there currently a way to register this other than maybe using a wonky regex?
<?php
Route::get('.+?\?.+?\bs={search}', 'SearchController@search');
// This regex is probably wrong, but you get what I was going for,
// and that kinda highlights why this is not an ideal way to do it
?>
例如,当您要捕获多个$ _GET参数时,这变得更难看:
This gets uglier when, say, you want to capture multiple $_GET params:
https://example.com/my-page?s=foobar&dept=clothing
我没有在Laravel文档中找到任何可让您在Route
$uri
参数上定义查询字符串选项的内容.推荐的选项是仅使用漂亮的URL(https://example.com/search/foobar
),但是肯定有保留查询字符串的有效用例.
I haven't found anything in Laravel docs that let you define query string options on the Route
$uri
parameter. The recommended option is to just use pretty URLs (https://example.com/search/foobar
), but there are definitely valid use cases for keeping query strings.
推荐答案
1:创建中间件( https ://laravel.com/docs/5.7/middleware ) 2:使用$ request-> query('s')验证传入请求 3:如果验证成功,则返回下一个,否则重定向到任何地方或显示错误响应
1: Create a middleware (https://laravel.com/docs/5.7/middleware) 2: Validate incoming request using $request->query('s') 3: If validation successfull return to next else redirect to wherever or display an error response
这篇关于存在某些查询字符串时定义Laravel路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!