Search Here

A Detailed Guide for implementing Laravel Maintainance Mode in your Project

A Detailed Guide for Implementing Laravel Maintainance Mode in your Project

Prepare Your Application for Maintainance Mode

By default, Laravel will automatically add CheckForMaintenanceMode middleware class to global middlewares in class app\Http\Kernal.php under protected $middleware = [ ... ] the property. The CheckForMaintenanceMode class is initially empty except a protected $except property where you specify which URL’s must be accessible when the application is in maintenance mode.

This class also inherits another use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware; which contains two methods they are handle and inExceptArray method.

  • The handle($request, Closure $next) method checks if the app is down for Maintainance by retrieving the file down from storage under the framework folder.
    Below is the snippet of this method.

    public function handle($request, Closure $next)
    {
        // check if app is down
        if ($this->app->isDownForMaintenance()) {
            // reads json data from down file
            $data = json_decode(file_get_contents($this->app->storagePath().'/framework/down'), true);
    
            // check if any specific IP address must be allowed to access the application.
            if (isset($data['allowed']) && IpUtils::checkIp($request->ip(), (array) $data['allowed'])) {
                return $next($request);
            }
    
            // checks if any routes must be allowed
            if ($this->inExceptArray($request)) {
                return $next($request);
            }
    
            //This throws maintainance exception
            throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
        }
    
        return $next($request);
    }
    
  • The inExceptArray($request) method returns boolean values which indicate whether to allowed the current route to access the site or not.
    here is how the snippet looks like.

    protected function inExceptArray($request)
    {
        foreach ($this->except as $except) {
            if ($except !== '/') {
                $except = trim($except, '/');
            }
    
            if ($request->fullUrlIs($except) || $request->is($except)) {
                return true;
            }
        }
    
        return false;
    }
    

An example snippet on Maintainance down file.

{
    "time": 1597294794,
    "message": "Here you'll have a custom message",
    "retry": null,
    "allowed": []
}

Exclude specific routes from maintenance

There is also a provision where you can allow certain routes to be accessible during your application maintenance mode.
In your project middleware app/Http/Middleware/CheckForMaintenanceMode.php you’ll find a protected property named as $except. The maintenance mode will not be applicable to those routes which are mentioned within $except.

protected $except = [
    'home',
    'order/*/edit', // for dynamic URL's
];

Note

You must include route URL and for dynamic URL’s use asterisks ( * )

Displaying a Custom Message During Maintainance Mode

When you execute the command php artisan down Laravel application creates a file named down at path storage\framework\down.
with this command you can also pass –message=”your custom message” as a parameter.
The command looks like below shown.

php artisan down --message="My Custom Message"

And another better way is that you edit down the file and update the key message with the customized maintenance message you want to display and its value is reflected in the template as well.

Note

Sometimes the customized message does get reflected into view. In such a case, clear your application cache and try again.

Udemy Laravel Course for Beginners

Udemy Laravel Course for Beginners

Displaying a Custom View or Template during Maintainance Mode

If you wish to choose your custom template insisted of default Laravel template than goto app\Exceptions\Handler.php and inside render($request, Throwable $exception) the method applies a conditioning checking.

First, check if the $exception object is the instanceOf the class MaintenanceModeException. And if true then return the custom template view.

Here is the snippet of how you can customize the template.
Create a view in resources\views\error-pages\maintenance-down.blade.php.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>This site is under maintainance</h1>
</body>
</html>

The next step is to go to app\Exceptions\Handler.php and update render() method.

use use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException; // don't forget to include this at the top
public function render($request, Throwable $exception)
{
 
    if( $exception instanceof MaintenanceModeException ){
        return response()->view('error-pages.maintenance-down', []);
    }

    return parent::render($request, $exception);
}

How to get out of maintenance mode

There is another command php artisan up which simply deletes the down file. Insist of running this command you yourself can manually delete that file.

Allow Specific IP’s to access during maintenance mode

You must specify list of those IP addresses which you wish to exclude from maintenance by using the below command.

php artisan down --allow=223.189.98.88 --allow=224.169.98.92

You can also manually specified in the down file within the allowed key.

Send JSON Response when requested via API

Use the $request->wantsJson() method to check where the client has request content in form of JSON then send the appropriate response.
In app\Exceptions\Handler.php.

public function render($request, Throwable $exception)
{

    if( $exception instanceof MaintenanceModeException ){

        if( $request->wantsJson() ){
            return response()->json([
                "error" => "We'r in maintainance mode"
            ], 503);
        }

        return response()->view('error-pages.maintenance-down', []);
    }

    return parent::render($request, $exception);
}
Laravel Maintainance Mode - send json response to API during maintainance mode

Laravel Maintainance Mode – send JSON response to API during maintenance mode

The Laravel documentation suggests you to use Envoyer to achieve zero downtime in maintenance mode. And also Laravel Queues will not work in maintenance mode.

Conclusion

You have reached the end of this post on A Detailed Guide for implementing Laravel Maintenance Mode in your Project. For any query or suggestion comment below.

Related Posts

Summary
Review Date
Reviewed Item
A Detailed Guide for Implementing Laravel Maintainance Mode in your Project
Author Rating
51star1star1star1star1star
Software Name
Laravel Web Development
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development