There is a cool feature in Laravel called Maintenance Mode that allows developer to simply take down the website and apply necessary updates and changes. You can invoke in the command prompt
php artisan down
and your application will put into maintenance mode. If you are done with your updates then you can put it on again by calling
php artisan up
this will enable your application again as normal with your changes and updates.
By default if you apply a php artisan down, and apply changes to your application, you can't test if your updates works fine unless you put you application up again. But then, if you put your application online again and you have some problem with the updates, your users might mess with the problem and will result to more problems.
In order for your to test your updates without pinpointing whether it works or not, you need to disable your application to your user but enable it with your workstation. This will allow you to test your application without worrying about users interacting with your application. We can do this by adding new Middleware to your application that will replace the current for maintenance mode.
by default in your Http\kernel.php in the $middleware variable you have \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,. The CheckForMaintenanceMode middleware is responsible for the maintenance mode toggle.
The $middleware variable will apply a middleware to all routes in your application while the $routeMiddleware are middleware the you can apply to every route you want to apply it.
Since we will create a new middleware that will override the existing one. Lets create a new middleware in your Http\Middleware directory and call it CheckForMaintenanceMode.php
with the follwing codes inside.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
class CheckForMaintenanceMode
{
protected $request;
protected $app;
public function __construct(Application $app, Request $request)
{
$this->app = $app;
$this->request = $request;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->app->isDownForMaintenance() &&
!in_array($this->request->getClientIp(), ['::1']))
{
throw new HttpException(503);
}
return $next($request);
}
}
You can specify multiple IP addresses you want to enable in maintenance mode and put it in the getClientIP() in array. If not found in the list of IP addresses then throws a HttpException for maintenance mode.
Now in your Http\kernel.php in the $middleware comment the existing one and add \App\Http\Middleware\CheckForMaintenanceMode::class, Maintenance mode will be applicable only to those IP addresses you have included in the array. Pretty cool.
Labels: Laravel