megavolkan
megavolkan

Reputation: 237

Laravel conditional routing based on database value

I'm developing an admin panel with laravel. I'm putting a preference for an end user to choose if the site is down (for maintenance or similar purpose). The preference will be stored as boolean in the database. Based on this value frontend will be routed to a custom view if the site is down.

(Site will be hosted on a shared host, no SSL. Using artisan commands are not an option.)

Currently, I can get "site_is_down" value from the database at boot time with a custom method in AppServiceProvider.php's register() method.

But I'm not sure how can I route calls based on this value in the routes file. I have two named route groups (Frontend and Backend) and standard Auth::routes() in routes/web.php. Only frontend routes should be conditionally routed. Backend and Auth should be excluded. (So the user can access Backend panel).

I'm trying to achieve something like this:

(I know this is not proper syntax, I'm trying to explain my mind)

<?php

if (config('global.site_is_down') === true) {
    //Route all frontend route group to maintenance view ->except(Backend and auth)
} else {
    //Route all as normal
}

Upvotes: 1

Views: 1869

Answers (1)

Anas Bakro
Anas Bakro

Reputation: 1409

Create a middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class CheckMaintainaceMode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (config('global.site_is_down')/*or what ever logic you need*/) {
            return redirect('mainainance-mode-url');
        }

        return $next($request);
    }
}

then use this middleware in frontend routes

Route::get('/frontend', function () {
    //
})->middleware('CheckMaintainaceMode');

or

Route::group(['middleware' => ['CheckMaintainaceMode']], function () {
    //
});

Upvotes: 2

Related Questions