Skip to content

Instantly share code, notes, and snippets.

@timothylhuillier
Created December 30, 2015 23:39
Show Gist options
  • Save timothylhuillier/36259055d9acb1a34380 to your computer and use it in GitHub Desktop.
Save timothylhuillier/36259055d9acb1a34380 to your computer and use it in GitHub Desktop.
Secure Middleware for Laravel 5

I noticed that Laravel 5 doesn't have a secure (https) middleware since the removal of filters. So i have re-implemented it and shared the code in the hope that you find it useful.

Installation

  • Add Secure.php to your app\Http\Middleware directory.
  • Add the secure middleware to your route.

Notes

  • If you are using route annotations, don't forget to re-scan your routes using the php artisan route:scan command.
  • The redirect is disabled in any non-production environment (as you likely won't have acquired a certificate at this stage).
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Routing\Middleware;
/**
* Secure
* Redirects any non-secure requests to their secure counterparts.
*
* @param request The request object.
* @param $next The next closure.
* @return redirects to the secure counterpart of the requested uri.
*/
class Secure implements Middleware
{
public function handle($request, Closure $next)
{
if (!$request->secure() && app()->environment('production')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment