How to create own helper functions in Laravel


Let’s create a Helpers directory under app and create a Helper.php file. These is an example:

<?php

function is_ssl($cf=false){
    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'){
        if($cf) return true;
        $_SERVER['HTTPS'] = 'on';
    }
    if($cf) return false;
    return isset($_SERVER['HTTPS']);
}

function https(){
    return is_ssl()?'https':'http';
}

If you are using a class and its methods are your helpers you can start the file with namespace declaration.

namespace App\Helpers;

Using service providers to load file

php artisan make:provider HelperServiceProvider

Result:

Administrator@tutorialspots MINGW64 /d/AppServ/www/tutorialspots
$ php artisan make:provider HelperServiceProvider
←[32mProvider created successfully.←[39m

This command will create file:
app/Providers/HelperServiceProvider.php

You can code your custom register method:

public function register()
{
    foreach (glob(app_path() . '/Helpers/*.php') as $file) {
        require_once($file);
    }
}

add this line:

App\Providers\HelperServiceProvider::class,

to your config/app.php

If your helper file use a class and you have specified namespace, you must add this line:

'Helper' => App\Helpers\Helper::class,

to your config/app.php

Done, now you can user all functions and class in your helper files anywhere.

Leave a Reply