【发布时间】:2020-01-26 21:13:40
【问题描述】:
我想让所有路由不区分大小写。
我已经看到了一些答案,但他们都在 Laravel 4 中进行了解释,我认为在 Laravel 5 中有更好的方法。
是否有任何提供程序或中间件可以用来覆盖传递的 url 并搜索它的小写匹配或类似的东西?
【问题讨论】:
我想让所有路由不区分大小写。
我已经看到了一些答案,但他们都在 Laravel 4 中进行了解释,我认为在 Laravel 5 中有更好的方法。
是否有任何提供程序或中间件可以用来覆盖传递的 url 并搜索它的小写匹配或类似的东西?
【问题讨论】:
在未来,你真的应该提供一个你已经尝试过的例子。
幸运的是,我已经将以下中间件放在一起。也许这将满足您的需求,或者至少为您指明发展自己的正确方向。
App\Http\Middleware\LowercaseRoutes.php
<?php
namespace App\Http\Middleware;
use Closure;
use \Illuminate\Support\Facades\Redirect;
class LowercaseRoutes
{
/**
* Paths excluded from lowercase restrictions
* Accepts wildcards (e.g., 'images*')
*
* @var array
*/
protected $excluded = [];
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// assert that route contains uppercase letters
$condition_1 = ! ctype_lower(preg_replace('/[^A-Za-z]/', '', $request->path()));
// assert that path is not root
$condition_2 = $request->path() !== "/";
// assert that path is not excluded from lowercase routes
$condition_3 = ! $request->is($this->excluded);
// rewrite route to lowercase if all conditions are met
if ($condition_1 && $condition_2 && $condition_3) {
$new_route = str_replace($request->path(), strtolower($request->path()), $request->fullUrl());
return Redirect::to($new_route, 301);
}
return $next($request);
}
}
【讨论】: