Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel custom helper - undefined index SERVER_NAME

In Laravel 5.1, I created a custom helper file: custom.php which I load in composer.json:

"autoload": {
    "files": [
        "app/Helpers/custom.php"
    ]
},

and it contains this method:

function website() {
    return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}

It works as expected, but every time I do php artisan commands, I get a call stack and this message:

Notice: Undefined index: SERVER_NAME in /path/to/custom.php on line 4

Why is this so? The method returns the correct value when run from within my Laravel app.

like image 414
Obay Avatar asked Mar 07 '16 06:03

Obay


1 Answers

$_SERVER['SERVER_Name'] global variable is only accessible when running your application through a browser. It will throw an error when you run your application through php-cli/through the terminal. Change your code to

function website() {
    
    if(php_sapi_name() === 'cli' OR defined('STDIN')){
        // This section of the code runs when your application is being run from the terminal
        return "Some default server name, or you can use your environment to set your server name"
    }else{
        // This section of the code run when your app is being run from the browser
        return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
    }
}

Hope this helps you.

like image 171
oseintow Avatar answered Sep 29 '22 20:09

oseintow