Last active
April 28, 2023 19:19
-
-
Save coreywelch/2de40f93a252da3b2eddc013a98b3d37 to your computer and use it in GitHub Desktop.
Here is a middleware class for laravel 5 that takes incoming routes and forces them to lowercase.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use \Illuminate\Support\Facades\Redirect; | |
class LowercaseRoutes | |
{ | |
/** | |
* Run the request filter. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
if(!ctype_lower(preg_replace('/[^A-Za-z]/', '', $request->path()))){ | |
$new_route = str_replace($request->path(), strtolower($request->path()), $request->fullUrl()); | |
return Redirect::to($new_route, 301); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this middleware.
A caveat with this is that you can't add it as a middleware group because the route has to match before the middleware is run on it. For example you can't use it like this:
... because the middleware won't run unless it matches the lowercased route in the first place!
So for those who don't want to have this on your global middleware stack, you can add a catch all route at the very end of your route file. Using the wildcard
where()
will ensure that the route matches and thus the middleware runs. This will only run the middleware if no other route matched so far just try a lowercased version of the route before hitting 404.Edit: WARNING! This has the possibility to break any packages that install their own routes, such as Nova. This is because they run AFTER your web.php and thus a catch-all in your web.php will STOP all routes that happen after it from working!
Edit: note that I have registered the middleware as 'lowercase' in the
$routeMiddleware
array in my Kernel.php.