问题
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.)
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
?>
This gets uglier when, say, you want to capture multiple $_GET params:
https://example.com/my-page?s=foobar&dept=clothing
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:
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
回答2:
That is very simple that depends on the parts of a url. The Route
class uses the "path string" of the url and you try to use the "parameters" of the url.
https://doepud.co.uk/blog/anatomy-of-a-url
In modern websites you should work with that structure because you get a better URL structure and it's much better for SEO and search engines.
You should use the parameters only in the function you call for small things which you can call over the $request->get('s');
method but then you have to redirect or you have to work in that function.
So don't fight the framework and work in that structure what is defined from the framework that all people who know the framework know how to work with it.
来源:https://stackoverflow.com/questions/53731266/defining-laravel-routes-when-certain-query-strings-are-present