How to define routes in Laravel that only work in a development environment?

Asked

Viewed 159 times

2

I would like to know how to define routes in Laravel that work only in development environment.

I believe that this can be useful to facilitate the debugs.

I want to be able to separate some routes to use only when it is in development and, in production, those routes do not exist.

How can I do that?

1 answer

2


In Laravel, it is possible to detect whether the environment in which the system is running on production or local.

The app/start/local.php file

In the case of local development, we have the file called app/start/local.php, which is only added to the application Laravel 4 if it is detected that the environment(environment) is marked as "local".

It would be possible to define some routes there and, thus, they would work only when the application was in development.

An example:

#app/start/local.php

Route::group(['prefix' => 'local'], function ()
{

    Route::get('login/{id}', function ($id)
    {
        $u = Usuario::findOrFail($id);

        Auth::login($u);

        return Redirect::to('/');
    });
});

In this case, when accessing the route localhost/local/login/1, we could authenticate a user in a simple way, without the need for a form. And this is something very useful for development to become more agile.

Methods for development environment detection

If there is a need to know in some piece of code that we are or are not in development environment, we have three ways to detect this, through methods present in Illuminate\Foundation\Application.

Example 1:

var_dump(App::isLocal()); //bool(true);

var_dump(App::environment('local')); // bool(true)

var_dump(App::environment() === 'local')); // bool(true)

I don’t know if it depends on the version of Laravel 4, but particularly like to use the first.

With this, it is possible to do the include of debug functions, for example when we are in development.

Example:

#app/start/global.php

if (App::isLocal()) 
    require app_path('local_functions.php');

Detecting the environment through the host used

It is also possible to define whether the application is in a local environment or not by simply checking the url of origin of the same.

The way I always use is to add some lines of code to the file bootstrap/start.php.

Thus:

$env = $app->detectEnvironment(function() use($app) {

    $enviromentsHosts = [
        'localhost',
        'url_virtualhost',

    ];

    if (in_array($app['request']->getHost(), $enviromentsHosts)) {

        return 'local';

    } else {

        return 'production';
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.