code-8
code-8

Reputation: 58760

How can I enable a certain route access only when a certain condition is true?

Goal

I'm trying to block my main login page base on a flag of my .env file. I'm not sure if this is the right approach.


Steps

In my .env I've added

LOGIN_PAGE=true

Then in my route file

I add that if check

if(env('LANDING_PAGE') == true){

    Route::get('/',['as' => 'login', 'uses'=>'AuthController@getSignIn']);
    Route::post('/', 'AuthController@postSignIn');
}

Result

LOGIN_PAGE=fasle

I go to my log-in page, I got 404 Page not found which is good.

LOGIN_PAGE=true

I go to my log-in page, I still got 404 Page not found which is not good. I should see my log-in page.

What did I forget ? How would one and go about and #GOAL

I'm trying to block my main login page base on a flag of my .env file. I'm not sure if this is the right approach.


Steps

In my .env I've added

LOGIN_PAGE=true

Then in my route file

I add that if check

if(env('LANDING_PAGE') == true){

    Route::get('/',['as' => 'login', 'uses'=>'AuthController@getSignIn']);
    Route::post('/', 'AuthController@postSignIn');
}

Result

LOGIN_PAGE=fasle

I go to my log-in page, I got 404 Page not found which is good.

LOGIN_PAGE=true

I go to my log-in page, I still got 404 Page not found which is not good. I should see my log-in page.

How would one enable a certain route access only when a certain condition is true?

Upvotes: 0

Views: 288

Answers (1)

teeyo
teeyo

Reputation: 3755

The best practice to what you are asking is to define a middleware that can be reused wherever and whenver you need it :

php artisan make:middleware CheckIsLandingPage

Then define the logic behinde your middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CheckIsLAndingPage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // your logic here 
        if (env('LANDING_PAGE') == true) {
           return redirect('somewhere');
        }

        return $next($request);
    }
}

Read more in the Laravel docs : https://laravel.com/docs/5.1/middleware#defining-middleware

Not much has changed in latest 5.5: https://laravel.com/docs/5.5/middleware#defining-middleware

Upvotes: 2

Related Questions