Enable maintenance mode in Laravel

Published by Manan Patel on

Recently I have integrated maintenance mode functionality in my Laravel project and I must tell you that it’s too easy to set up on any Laravel project without any troubles.

Let’s say I have two types of user roles:

  1. Super Admin
  2. Business Owner

And I want to access login & super admin group routes even If maintenance mode is enabled just like WordPress.

Now let’s jump to the code.

Step1:

Create new custom middleware.

php artisan make:middleware CheckForMaintenanceMode

Step 2: 

After creating middleware open CheckForMaintenanceMode.php file from app/Http/Middleware directory and replace with this code.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;

class CheckForMaintenanceMode
{
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function handle($request, Closure $next)
    {
        if ($this->app->isDownForMaintenance() && !$this->isBackendRequest($request)) {
            $data = json_decode(file_get_contents($this->app->storagePath() . '/framework/down'), true);

            throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
        }

        return $next($request);
    }

    private function isBackendRequest($request)
    {
        return ($request->is('login') or $request->is('admin/*') or $request->is('api/*'));
    }
}

Inside isBackendRequest function, you can define routes which you want to allow even If maintenance mode is enabled.

Step 3:

Now we have to include CheckForMaintenanceMode middleware inside Kerel.php file and for that navigate to app/Http directory.

Here you have to do two things:

1. Add below one line of code inside protected $middleware = [ … ]

'App\Http\Middleware\CheckForMaintenanceMode',

2. Remove CheckForMaintenanceMode::class code from protected $middleware = [ … ]

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

Step 4:

To make your site Online/Offline, create a new form with drop-down selection(Online/Offline) inside your admin panel and manage flag into the database (is_online 1/0). Whenever admin user changes the site availability, run Artisan code based on the selection.

if ($request->get('is_online') == '1') {
    \Artisan::call('up');
} else {
    \Artisan::call('down');
}

Keep visiting for new stuff and give your feedback.

Happy Coding 😉


1 Comment

baldevp2 · January 29, 2019 at 5:24 am

I searched a lot in google, but not found this is very help full to me. Thank you so much Manan Patel.

Leave a Reply

%d bloggers like this: